javascript - 单击数组中的按钮时如何执行函数?
问题描述
我在图表上布置了一个非常大的 256 个按钮数组(例如,它只有 5 个)。我已经创建了一个带有事件侦听器的 forEach 语句,但它并没有做我想要它做的事情。我希望我单击的按钮变成简单的黑色,但我尝试设置一个 console.log 来测试我的功能,每次单击一个按钮它都会记录 256 次。我希望按钮仅对我在数组中单击的按钮执行操作。
let cells = document.querySelectorAll(".grid");
cells.forEach(() => {
addEventListener("click", function(){
target.style.backgroundColor = "black";
});
});
body {
margin:0;
}
#background {
position:absolute;
height:800px;
width:800px;
background-color:grey;
top:100px;
left:550px;
display:grid;
grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}
.grid {
display:block;
height:50px;
width:50px;
}
.grid:hover {
background-color:lightgrey;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FindMyKeys</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="background">
<div id="grid1" class="grid"></div>
<div id="grid2" class="grid"></div>
<div id="grid3" class="grid"></div>
<div id="grid4" class="grid"></div>
<div id="grid5" class="grid"></div>
</div>
<script src="app.js"></script>
</body>
</html>
解决方案
为什么大家都忽略 JS 事件委托?!!(我已经更改了片段使用的 css 值)
document.querySelector("#background").onclick = function (e) {
if (e.target.className !== 'grid') return;
e.stopPropagation();
e.target.style.backgroundColor = "black";
}
body {
margin: 0;
}
#background {
position: absolute;
height: 100px;
width: 400px;
background-color: grey;
top: 100px;
left: 10px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}
.grid {
display: block;
height: 50px;
width: 50px;
}
#background div {
background-color: pink;
}
.grid:hover {
background-color: lightgrey;
}
<div id="background">
<div id="grid1" class="grid"></div>
<div id="grid2" class="grid"></div>
<div id="grid3" class="grid"></div>
<div id="grid4" class="grid"></div>
<div id="grid5" class="grid"></div>
</div>
推荐阅读
- nginx - Nginx fastcgi缓存url匹配首页
- centos - 如何在 CentOS 6 上安装 devtoolset-7 i686?
- python - 使用 MultiIndex 将值的子集分配给 pandas 数据框
- python - 如何将 tinkergraph 上传到 python/gremlin?
- node.js - 如何将画布 json 转换为 base64image?
- wordpress - 如果 ACF 日期已通过 WordPress 中的 Cron Job 更新帖子类别
- windows - Python:打开自动生成的文件
- karate - 空手道 - [#document: null] 在输出中
- c++ - 为什么我收到错误无法在 cmake 中找到源文件?
- python - 在土耳其语中使用 Spacy