问题
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