javascript - 带有 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);
有人能发现我犯的错误吗?
解决方案
代码与您提供的链接之间存在一些差异。里面没有任何功能doit()
。
您已附加addEvenListener
到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>
您还可以使用Array.prototype.forEach()
witharrow 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>
推荐阅读
- sql-server - Is there a way to test against a SQL Server databse in a build pipeline?
- python - 如何将 int 转换为 hex 并将 hex 写入文件?
- angular - 为routerlink url添加书签并返回它不起作用
- django - 如何使用模型实例中的值预填充正常形式
- jenkins - Jenkins Pipeline Openshift 插件
- .net - 我的整个解决方案是否必须是 .NET Framework 而不是 .NET Core,因为我使用了需要 .NET Framework 的 NuGet 包?
- python - 你如何在数字之间创建一个数组范围?
- unity3d - 为什么我可以在这个函数上使用 no void 或 return value
- javascript - 未捕获的类型错误:e 不是书签的 JS 函数上的函数
- java - 如何在android中调整位图的大小