-
Notifications
You must be signed in to change notification settings - Fork 6
遍历DOM节点的正确方法 #68
Copy link
Copy link
Closed
Labels
Description
正文
用 document.querySelectorAll 获取到一批 DOM 节点之后,常常需要遍历这些节点,为每个节点绑定对应的事件。
在 JavaScript closure inside loops – simple practical example 中虽然讲到可以用 forEach、let,但是在部门的 iPhone 4、三星平板这两部旧设备上,无法使用这些新特性。
上网查了一下,在 Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function” 中讲到,用 document.querySelectorAll 之类的方法获取到的 DOM 节点,是 HTMLCollection,是“类数组对象”,所以在一些旧设备上,是无法使用 forEach 这样的方法来遍历 DOM 节点的。
最保险的方法,就是采用最原始的 for 循环来遍历这些 DOM 节点,绝对不会出错。
参考资料
Reactions are currently unavailable