首页 > 解决方案 > 事件监听器仅适用于最后创建的元素

问题描述

我试图在屏幕上生成 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;
}​

标签: javascriptclassdom

解决方案



推荐阅读