首页 > 解决方案 > 单击数组中的按钮时如何执行函数?

问题描述

我在图表上布置了一个非常大的 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>

标签: javascripthtmlcss

解决方案


为什么大家都忽略 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>


推荐阅读