我被要求将我的Javascript代码重构为多个函数(其中每个函数都执行一件事),而且我不知道该怎么做。我需要我的显示赋值操作是两个独立的函数,所有的值都应该作为参数/参数传递给函数,所以没有全局变量。我甚至不知道从哪里开始,我觉得这应该很容易,但我在这里绞尽脑汁。在JavaScript中,我该如何将显示分配操作提取到两个函数中,每个函数接受一个元素参数?
下面是HTML:
<body onload="changeChooser()">
<h1>Monster Mash</h1>
<p>Pick your favorite monster from the dropdown!</p>
<select id="monsterChooser" onchange="changeChooser();">
<option value="monsterContent">Monsters</option>
<option value="frankContent">Frankenstein</option>
<option value="draculaContent">Dracula</option>
<option value="wolfmanContent">Wolfman</option>
<option value="mummyContent">Mummy</option>
<option value="piggyContent">I hate monsters</option>
</select>
<div id="monsterContent">
<h2>Monster Madness</h2>
<img src="images/monsters.jpg">
</div>
<div id="frankContent">
<h2>Frankenstein</h2>
<img src="images/frankenstein.jpg">
</div>
<div id="draculaContent">
<h2>Dracula</h2>
<img src="images/dracula.jpg">
</div>
<div id="wolfmanContent">
<h2>Wolfman</h2>
<img src="images/wolfman.jpg">
</div>
<div id="mummyContent">
<h2>Mummy</h2>
<img src="images/mummy.jpg">
</div>
<div id="piggyContent">
<h2>FINE!</h2>
<p>Here is a little piggy eating ice cream!</p>
<img src="images/piggy.jpg">
</div>
</body>
</html>
这里是JavaScript
<script>
function changeChooser() {
console.log("gotChange");
var chooser = document.getElementById("monsterChooser");
var options = chooser.options;
var counter = 0;
while (counter < options.length) {
if (options[counter].selected) {
document.getElementById(options[counter].value).style.display = "";
} else {
document.getElementById(options[counter].value).style.display = "none";
}
counter = counter + 1;
}
}
</script>