我正在尝试创建一个for循环以缩短我的代码,但是当我测试代码并尝试使所有单个方块在单击时消失时,只有最后一个正在消失而其他的仍然存在。我很困惑,因为控制台也没有给我任何错误!
请参阅我的原始长码,针对每个方格:
document.getElementById("square1").onclick = function disappear() {
document.getElementById("square1").style.visibility = "hidden";
}
document.getElementById("square2").onclick = function disappear() {
document.getElementById("square2").style.visibility = "hidden";
}
document.getElementById("square3").onclick = function disappear() {
document.getElementById("square3").style.visibility = "hidden";
}
document.getElementById("square4").onclick = function disappear() {
document.getElementById("square4").style.visibility = "hidden";
}
document.getElementById("square5").onclick = function disappear() {
document.getElementById("square5").style.visibility = "hidden";
}
document.getElementById("square6").onclick = function disappear() {
document.getElementById("square6").style.visibility = "hidden";
}
这是我创建的for循环,试图缩短我的代码:
for (var i = 1; i < 7; i++) {
var squaresDis = document.getElementById("square" + i);
document.addEventListener("click", function disappear() {
squaresDis.style.visibility = "hidden";
}
)};