javascript - 事件监听器仅适用于最后创建的元素
问题描述
我试图在屏幕上生成 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;
}
解决方案
推荐阅读
- vaadin - 添加具有不可见列值的表项
- python - 为什么 Python3.6 显示出比 3.7 更好的结果?
- django - Django、Nginx、uwsgi、Kubernetes:无法将 nginx 连接到 uwsgi 流
- python - 如何在图像的特定区域应用膨胀?
- typescript - 打字稿中`import x = require('x')`和`const x = require('x')`之间的区别
- jquery - 如何在单击 div 时在 div 内的隐藏按钮上触发事件
- python - Django 表单 - SelectMultiple 更改可见值
- json - 将动态 Json 对象解析为 VB 类
- mysql - 如何减少sql语句的查询时间,mysql
- java - 我应该如何将这些对象存储在 SQLite 数据库中?