所以我是一个 javascript 菜鸟。我正在为网页设计类(class)做作业,我们正在练习事件监听器。所以我必须将变量分配给3个单独的div,将它们放在一个数组中,创建一个函数来使它们显示或隐藏,并使用按钮/单击事件监听器来调用函数来分别调用或隐藏它们。这是我的代码:
var greenBox = document.getElementById("greenBox");
var redBox = document.getElementById("redBox");
var blueBox = document.getElementById("blueBox");
var showALL = document.getElementById("showAll");
var hideALL = document.getElementById("hideAll");
var boxes = [greenBox, redBox, blueBox];
function showBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "block";
}
}
function hideBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "none";
}
}
showALL.addEventListener("click", function() {
showBoxes(boxes);
})
// The "Hide All" button invokes the hideBoxes method
hideALL.addEventListener("click", function() {
hideBoxes(boxes);
})
<form action="#">
<input type="button" id="showAll" value="Show All"><br />
<input type="button" id="hideAll" value="Hide All"><br />
</form>
<div class="box" id="greenBox" style="display:none"></div>
<div class="box" id="redBox" style="display:none"></div>
<div class="box" id="blueBox" style="display:none"></div>
那我到底做错了什么?我已经检查了多次是否有拼写错误等,但对我来说一切看起来都不错?但它仍然不起作用。
最佳答案
document.getElementById
区分大小写。
当您搜索 document.getElementById("showALL");
时,您会得到 id="showAll"
。
选择一个一致的案例,它应该可以工作。
var greenBox = document.getElementById("greenBox");
var redBox = document.getElementById("redBox");
var blueBox = document.getElementById("blueBox");
var showALL = document.getElementById("showAll");
var hideALL = document.getElementById("hideAll");
var boxes = [greenBox, redBox, blueBox];
function showBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "block";
}
}
function hideBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "none";
}
}
showALL.addEventListener("click", function() {
showBoxes(boxes);
})
// The "Hide All" button invokes the hideBoxes method
hideALL.addEventListener("click", function() {
hideBoxes(boxes);
})
.box {width: 200px; height: 36px;}
#redBox {background-color: #F00;}
#greenBox {background-color: #0F0;}
#blueBox {background-color: #00F;}
<form action="#">
<input type="button" id="showAll" value="Show All"><br />
<input type="button" id="hideAll" value="Hide All"><br />
</form>
<div class="box" id="greenBox" style="display:none"></div>
<div class="box" id="redBox" style="display:none"></div>
<div class="box" id="blueBox" style="display:none"></div>
关于javascript - 事件监听器在 javascript 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016681/