【问题标题】:How to make each of my divs perform the same function, but individually?如何让我的每个 div 执行相同的功能,但单独执行?
【发布时间】:2022-01-07 16:23:58
【问题描述】:

我正在制作 Etch-a-Sketch。我目前有一定数量的 div。他们每个人都共享一个类和事件侦听器。我对每个函数都使用了一个,以便它们都遵循相同的事件。当我单击任何 div 时,它们都会变成蓝色。我希望我单击的一个 div 变为蓝色,而不是同时将它们全部变为蓝色。这是我的代码,我该怎么做才能使我单击的项目发生变化,而不是所有项目都发生变化。

function makeRows(rows, cols){
for (let i = 0; i < (rows * cols); i++){
  let container= document.getElementById("container");
 let cell= document.createElement("div");
  cell.innerText = (i + 1);
  cell.setAttribute('id','box');
  container.appendChild(cell).className = "box"; 
}
};

makeRows(16,16);

//events


document.querySelectorAll('.box').forEach(box => {
  box.setAttribute("style", "background-color: red;");
});

document.addEventListener('click', changeColor);

function changeColor(){
  document.querySelectorAll('.box').forEach(box => {
  box.setAttribute("style", "background-color:blue ;");
});
  
}


【问题讨论】:

    标签: javascript foreach click


    【解决方案1】:

    您正在使用事件委托,因此您需要查看点击了什么。您可以使用事件目标来做到这一点。

    function makeRows(rows, cols) {
      for (let i = 0; i < (rows * cols); i++) {
        let container = document.getElementById("container");
        let cell = document.createElement("div");
        cell.innerText = (i + 1);
        // cell.setAttribute('id', 'box'); useless
        container.appendChild(cell).className = "box";
      }
    };
    
    makeRows(16, 16);
    
    document.addEventListener('click', changeColor);
    
    function changeColor(evt) {
      const box = evt.target.closest(".box");
      if (box) {
        box.classList.toggle("selected");
      }
    
    }
    .box {
      width: 50px;
      height: 50px;
      display: inline-block;
    }
    
    .box.selected {
      background-color: blue;
    }
    &lt;div id="container"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      现在您正在向整个文档添加一个事件侦听器。

      document.addEventListener('click', changeColor);
      

      当您单击文档时,它将触发您的 changeColor() 函数,该函数循环遍历每个框并将它们全部变为蓝色。

      你想要的是每个 BOX 都有自己的事件监听器,当点击它时会改变它自己的颜色。

      现在很清楚了:

          document.querySelectorAll('.box').forEach(box => {
            box.addEventListener("click", ()=>{
                box.setAttribute("style", "background-color:blue ;");
             }
          });
      

      对于每个盒子,给那个盒子它自己的事件监听器。点击后,更改样式。

      尽管如此,epascarello 的回答比我的要好得多,但我希望逻辑是有道理的。

      【讨论】:

        猜你喜欢
        • 2017-09-17
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2014-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多