[英]JS - add click event listener for all elements matching a querySelectorAll
I have li elements to which I'm trying to add click events that match the querySelector : .sidebar-nav li:not(.top)
.我有 li 元素,我试图向其中添加与 querySelector 匹配的点击事件: .sidebar-nav li:not(.top)
。 I have this code :我有这个代码:
var sidebarItems = document.querySelectorAll(".sidebar-nav li:not(.top)");
// For each sidebar item, register a click function
for (var i = 0; i === sidebarItems.length; i++) {
sidebarItems[i].addEventListener("click", function() {
console.log("fromage");
})
};
However, no event listeners are added.但是,没有添加事件侦听器。 The firefox dev tools show nothing, and nothing logs to the console when I click an element.当我单击一个元素时,firefox 开发工具没有显示任何内容,也没有任何内容记录到控制台。 I checked in the JS console, sidebarItems has the correct node list.我检查了 JS 控制台, sidebarItems 有正确的节点列表。
Any help?有什么帮助吗?
A for
loop will loop for as long as the condition is true.只要条件为真, for
循环就会循环。
Your condition is i === sidebarItems.length
so unless the length is 0
, it will never be true.你的条件是i === sidebarItems.length
所以除非长度是0
,否则它永远不会是真的。
Loop while i
is less then the length of the array-like object.当i
小于类数组对象的长度时循环。
for (let i = 0; i < sidebarItems.length; i++) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.