我在图形上布置了一个非常大的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>
只需forEach
稍微改变一下即可:
cells.forEach((cell) => {
cell.addEventListener("click", function(event){
event.target.style.backgroundColor = "black";
});
});
如果单元格始终位于元素内,则可以使用事件冒泡来发挥自己的优势:
document.getElementById("background").addEventListener("click", function(event) {
if (event.target.className == "grid") {
event.target.style.backgroundColor = "black";
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句