javascript 带有 classList 的 querySelectorAll() 上的 addEventListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50643302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:13:51  来源:igfitidea点击:

addEventListener on a querySelectorAll() with classList

javascriptaddeventlistener

提问by Evan

I am trying to add an event listener but no result came. I know JavaScript has a hoisting feature but I believe I tried all except the correct solution.

我正在尝试添加一个事件侦听器,但没有结果。我知道 JavaScript 具有提升功能,但我相信除了正确的解决方案外,我尝试了所有其他方法。

const cbox = document.querySelectorAll(".box");
function doit() {
    for (let i = 0; i < cbox.length; i++){
        cbox[i].classList.add("red");
    }
}
cbox.addEventListener("click", doit,false);

Can somebody spot the mistake I make?

有人能发现我犯的错误吗?

回答by Mamun

There are some dissimilarities between the code and the link you have provided. There is no function doit()in there. You have attached addEvenListenerto the NodeListin cbox.addEventListener("click",.....

代码和您提供的链接之间存在一些不同之处。doit()里面没有任何功能。您已连接addEvenListenerNodeListcbox.addEventListener("click",.....

Try the following:

请尝试以下操作:

const cbox = document.querySelectorAll(".box");

 for (let i = 0; i < cbox.length; i++) {
     cbox[i].addEventListener("click", function() {
       cbox[i].classList.toggle("red");
     });
 }
*,
html,
body {
    padding: 0;
    margin: 0;
}

.box {
    width: 10rem;
    height: 10rem;
    background-color: yellowgreen;
    float: left;
    position: relative;
    margin: 0.5rem;
    transition: .5s all;
}

h3 {
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.box:not(:first-child) {
    margin-left: 1rem;
}

.red {
    background-color: orangered;
}
<div id="box1" class="box box1">
    <h3>Box 1</h3>
</div>
<div id="box2" class="box box2">
    <h3>Box 2</h3>
</div>
<div id="box3" class="box box3">
    <h3>Box 3</h3>
</div>
<div id="box4" class="box box4">
    <h3>Box 4</h3>
</div>

回答by Riad ZT

You can you the forEach on the class or you Can use Event delegation.

你可以在类上使用 forEach 或者你可以使用事件委托。

const cboxes = document.querySelectorAll(".box");
function doit() {
    ... do something ...
}
cboxes.forEach(
  function(cbox) {
   cbox.addEventListener("click", doit,false);
  }
);

Notice that I changed your variable name.

请注意,我更改了您的变量名称。

EventDelgation

事件委托

HTML:

HTML:

<div id="parent">
  <div id="box1" class="box box1">
    <h3>Box 1</h3>
  </div>
  <div id="box2" class="box box2">
      <h3>Box 2</h3>
  </div>
  <div id="box3" class="box box3">
      <h3>Box 3</h3>
  </div>
  <div id="box4" class="box box4">
      <h3>Box 4</h3>
  </div>
</div>

The JS part:

JS部分:

const parent = document.querySelector("#parent");

parent.addEventListener('click', (e) => {
  e.target.classList.add('red');
  console.log(e.target);
});

Event delegation is much better and it uses fewer resources, as you only use 1 Event listener and no for loop.

事件委托要好得多,它使用的资源更少,因为您只使用 1 个事件侦听器而没有 for 循环。

回答by leonheess

ES6 makes this a bit simpler:

ES6 让这更简单一点:

document.querySelectorAll(".box").forEach(box => 
    box.addEventListener("click", () => box.classList.toggle("red"))
);

Example implementation:

示例实现:

document.querySelectorAll(".box").forEach(box => 
    box.addEventListener("click", () => box.classList.toggle("red"))
);
.box {
    width: 5rem;
    height: 5rem;
    background-color: yellowgreen;
    display: inline-block;
}

.box.red {
    background-color: firebrick;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>