添加事件监听器

时间:2020-02-29 08:11:05

标签: javascript css dom css-selectors dom-events

我们如何仅在代码的每个项目上添加一次事件侦听器,所以在react中很容易进行状态管理,但是我们该如何使用普通的旧javascript

     <div class="grid-container" id="ad">
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>   
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      <div class="grid-item" ></div>
      </div>


   let divs = document.querySelectorAll(".grid-item")

        for(let i=0;i<divs.length;i++) { 

            divs[i].addEventListener("click", function() {
            divs[i].style["background-color"] = "red";

        });
    }

2 个答案:

答案 0 :(得分:3)

您需要使用命名函数而不是匿名函数。然后使用该命名函数以添加所有侦听器的方式删除所有侦听器。

这是一个jsfiddle示例: https://jsfiddle.net/v1akgpL6/

let divs = document.querySelectorAll(".grid-item");

/* Remove all event listeners */
const removeListeners = () => {
    for (let j = 0; j < divs.length; j++) { 
    divs[j].removeEventListener("click", clickHandler);
  }
}

/* Click event listener */
const clickHandler = (e) => {
  e.currentTarget.style["background-color"] = "red";
  removeListeners();
}

/* Add event listeners */
for (let i = 0; i < divs.length; i++) {
    divs[i].addEventListener("click", clickHandler);
}

答案 1 :(得分:2)

您可以在事件侦听器中使用options对象,使事件仅发生一次,如下所示:

let divs = document.querySelectorAll(".grid-item");
const changeBackgroundColor = e => {
 e.target.style.backgroundColor = "red";
 }
divs.forEach(div => {
 div.addEventListener("click", changeBackgroundColor, {once: true});
})