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

一笑奈何 提交于 2021-01-28 05:40:38

问题


When I use simple for loop, addEventListener works well in for loop.

But when I use for-in loop, it makes error like

Uncaught TypeError: checklist[i].addEventListener is not a function

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!


回答1:


The problem is that for-in loop iterates over all enumerable properties of an array or object. 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. So you can't add an event listener to them.



来源:https://stackoverflow.com/questions/46518787/addeventlistener-works-in-simple-for-loop-but-doesnt-work-with-for-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!