[英]Event listener only applying to last created element
我试图在屏幕上生成 5 个方块,当我将鼠标悬停在其中一个方块上时,方块的背景颜色变为黑色。 将鼠标悬停在元素上后,我将“命中”类应用于该元素。 命中类仅应用于已生成的最后一个方块。 但不适用于任何其他人。 我查看了其他一些我知道与我的类似的 stackoverflow 问题,但我似乎无法找到答案,因为我没有在我的 javaScript 代码中修改 innerHTML。
我不能在这个项目中使用 JQuery。
HTML代码:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Etch A Sketch</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div id="grid">
</div>
<script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>
JavaScript 代码:
let grid = document.querySelector("#grid"); //The grid is the border that surrounds all of the squares
for (i=0; i < 5; i++) {
square = document.createElement("div");
square.classList.add("square"); //The "square" class creates the square out of the div
grid.appendChild(square);
}
square.addEventListener("mouseover", function () {
square.classList.add("hit"); //The "hit" class just changes the background color of the square to black
})
CSS代码:
.square {
display: inline-grid;
width: 31px;
height: 31px;
border: 3px solid black;
}
.hit {
background-color: black;
}
#grid {
position: absolute;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
width: 500px;
height: 500px;
border: 3px solid black;
}
该类仅应用于最后一个元素,因为您将事件侦听器添加到循环之外,因此它仅将其应用于square
的最后一个实例。 另请注意,您应该在使用之前声明您的变量。 在您的示例中,您使用square
而无需对其进行初始化。 看这里:
let grid = document.querySelector("#grid"); //The grid is the border that surrounds all of the squares for (i = 0; i < 5; i++) { let square = document.createElement("div"); square.classList.add("square"); //The "square" class creates the square out of the div grid.appendChild(square); square.addEventListener("mouseover", function() { square.classList.add("hit"); //The "hit" class just changes the background color of the square to black }) }
.square { display: inline-grid; width: 31px; height: 31px; border: 3px solid black; } .hit { background-color: black; } #grid { position: absolute; top: 50%; left: 50%; margin-top: -250px; margin-left: -250px; width: 500px; height: 500px; border: 3px solid black; }
<div id="grid"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.