gpt4 book ai didi

javascript - 返回数组中的每个 DOM 元素

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:24 24 4
gpt4 key购买 nike

我在实验中使用了 3 种方法来返回数组中的每个 HTML 元素:

  • elementsArray.forEach(function(elem) {})
  • [].forEach(elementsArray, function(elem) {})
  • Array.prototype.forEach.call(elementsArray, function(elem) {})


在我的 HTML 中,我有以下元素:

<section id="example">
<div></div>
<div></div>
<div></div>
</section>


第一个例子:

var query = document.querySelector.bind(document);

query('#example').children.forEach(function(elem) {
console.log(elem);
})

Uncaught TypeError: query(...).children.forEach is not a function


第二个例子:

var query = document.querySelector.bind(document);

[].forEach(query('#example').children, function(elem) {
console.log(elem);
})

Uncaught TypeError: #<HTMLCollection> is not a function


第三个例子:

var query = document.querySelector.bind(document);

Array.prototype.forEach.call(query('#example').children, function(elem) {
console.log(elem)
})

<div></div>
<div></div>
<div></div>

我的问题是,是什么让这三者在返回 DOM 元素方面彼此不同?我应该什么时候使用它们?

最佳答案

第一个例子:

元素的children 属性是一个HTMLCollection,它没有forEach 方法。所以这个选项不起作用。

第二个例子:

[].forEach(query('#example').children, function(elem) {

这尝试使用子 HTMLCollection 作为回调函数。这不是一个函数,所以这不起作用。

你可以这样做:

[].forEach.call(query('#example').children, function(elem) {

第三个例子:

Array.prototype.forEach.call 大致等同于 [].forEach.call 方法,只是它不创建新的数组对象。这个会起作用。

另一种选择:

另一个略有不同的选项是使用 querySelectorAll,它返回 NodeList ,它确实有一个 forEach 方法。

var queryAll = document.querySelectorAll.bind(document);

queryAll('#example > *').forEach(function(elem) {
console.log(elem);
})

不过,NodeListforEach方法是较新加入的,浏览器支持还很欠缺。不过,您可以对其进行 polyfill。

关于javascript - 返回数组中的每个 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com