带有 classList 的 querySelectorAll() 上的 addEventListener

新手上路,请多包涵

我正在尝试添加一个事件侦听器,但没有结果。我知道 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);

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

原文由 Evan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 559
2 个回答

代码与您提供的链接之间存在一些差异。那里没有函数 doit()

您已将 addEvenListener 附加到 NodeListcbox.addEventListener("click",..... ,您必须遍历当前列表并附加事件:

尝试以下操作:

 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>

您还可以将 Array.prototype.forEach()arrow function 语法一起使用,这样您就可以用更少的代码实现相同的目的:

 let cbox = document.querySelectorAll(".box");
cbox.forEach(box => {
  box.addEventListener('click', () => box.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>

原文由 Mamun 发布,翻译遵循 CC BY-SA 4.0 许可协议

ES6 使这更简单一些:

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

示例实现:

 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>

原文由 leonheess 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题