带有classList的querySelectorAll()上的addEventListener [英] addEventListener on a querySelectorAll() with classList

查看:137
本文介绍了带有classList的querySelectorAll()上的addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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?

推荐答案

代码与您提供的链接之间存在一些差异.那里没有功能doit().您已将addEvenListener附加到cbox.addEventListener("click",.....

There are some dissimilarities between the code and the link you have provided. There is no function doit() in there. You have attached addEvenListener to the NodeList in cbox.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>

这篇关于带有classList的querySelectorAll()上的addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆