简体   繁体   English

addEventListener在简单的for循环中工作,但在for-in循环中不工作

[英]addEventListener works in simple for loop but doesn't work with for-in loop

When I use simple for loop, addEventListener works well in for loop. 当我使用简单的for循环时,addEventListener在for循环中效果很好。

But when I use for-in loop, it makes error like 但是当我使用for-in循环时,会出现类似

Uncaught TypeError: checklist[i].addEventListener is not a function 未捕获的TypeError:checklist [i] .addEventListener不是函数

This is my work-well code. 这是我的工作代码。

var checklist = document.querySelectorAll(".checklist");
for (var i = 0, len = checklist.length; i < len; i += 1) {
  checklist[i].addEventListener('change', function (event) {
    alert('test');
  });
}

This is my Error code. 这是我的错误代码。

var checklist = document.querySelectorAll(".checklist");
for (var i in checklist) {
  checklist[i].addEventListener('change', function (event) {
    alert('test');
  });
}

I don't know what is difference between two codes. 我不知道两个代码之间有什么区别。 Please Help me. 请帮我。 Thanks! 谢谢!

The problem is that for-in loop iterates over all enumerable properties of an array or object. 问题在于for-in循环会迭代数组或对象的所有可枚举属性。 So, if you log your variable in console you'll see that along with the indexes of the elements you also get other properties like length , keys , values of the array and checklist[length] or checklist[keys] are not DOM elements. 因此,如果您在控制台中记录变量,您将看到元素的索引以及其他属性,例如lengthkeys ,数组的valueschecklist[length]checklist[keys]都不是DOM元素。 So you can't add an event listener to them. 因此,您无法向他们添加事件监听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM