问题描述
我的HTML中具有类node-item
的一些元素,我可以使用以下方式在组件中访问它们:
I have some elements in my HTML with class node-item
, I access them in my component using:
let nodeItems = document.getElementsByClassName('node-item');
当我登录nodeItems
时,它会给我一个长度为4的HTMLCollection[]
.
and when I log nodeItems
it gives me a HTMLCollection[]
with length 4.
我尝试了很多方法,但是仍然无法在nodeItems
上进行迭代:
I tried many ways but still can't iterate on nodeItems
:
1-首先尝试:
let bar = [].slice.call(nodeItems);
for (var g of bar){
console.log(g); //gives me nothing
}
2秒尝试:
for(let c of <any>nodeItems) {
console.log(c); //gives me nothing
}
我尝试了数组迭代和对象迭代,但是仍然是undefined
或error
.还尝试过:
And I tried array iteration and object iteration but still undefined
or error
. also tried:
let nodeItems = document.querySelector(selectors);
但是同样的问题.
推荐答案
nodeItems
是HTMLCollection
,它是类似数组的对象.
nodeItems
is HTMLCollection
, which is array-like object.
在现代浏览器中它是可迭代的.在启用 downlevelIteration
编译器选项的情况下,支持迭代器.将是:
It is iterable in modern browsers. Iterators are supported with downlevelIteration
compiler option enabled, in this case it will be:
const nodeItems = document.getElementsByClassName('node-item');
for (const c of nodeItems) {
// ...
}
可迭代项可以在较旧的浏览器中进行填充. core-js
为DOM可迭代项提供 polyfills .
Iterables can be polyfilled in older browsers. core-js
provides polyfills for DOM iterables.
否则,nodeItems
可以转换为数组并照常进行迭代:
Otherwise nodeItems
can be converted to array and iterated as usual:
const nodeItems = Array.from(document.getElementsByClassName('node-item'));
for (const c of nodeItems) {
// ...
}
这篇关于如何在HTMLCollection上进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!