addEventListener可在简单的for循环中使用,但不适用于for-in循环 [英] addEventListener works in simple for loop but doesn't work with for-in loop

查看:123
本文介绍了addEventListener可在简单的for循环中使用,但不适用于for-in循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用简单的for循环时,addEventListener在for循环中效果很好.

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

但是当我使用for-in循环时,会出现类似的错误

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

未捕获的TypeError:检查表[i] .addEventListener不是函数

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

这是我的工作代码.

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

这是我的错误代码.

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!

推荐答案

问题是 for-in 循环迭代数组或对象的所有可枚举属性.因此,如果您在控制台中记录变量,您将看到元素的索引以及其他属性,例如 length keys values <数组的/code>和 checklist [length] checklist [keys] 不是DOM元素.因此,您无法向他们添加事件监听器.

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.

这篇关于addEventListener可在简单的for循环中使用,但不适用于for-in循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆