[英]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.