Skip to content

遍历DOM节点的正确方法 #68

@Dream4ever

Description

@Dream4ever

正文

document.querySelectorAll 获取到一批 DOM 节点之后,常常需要遍历这些节点,为每个节点绑定对应的事件。

JavaScript closure inside loops – simple practical example 中虽然讲到可以用 forEachlet,但是在部门的 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 节点,绝对不会出错。

参考资料

Metadata

Metadata

Assignees

No one assigned

    Labels

    Front-endEverything you see and experienceJSJavascript

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions