如何正确迭代 getElementsByClassName [英] How to correctly iterate through getElementsByClassName
问题描述
我是 Javascript 初学者.
I am Javascript beginner.
我正在通过 window.onload
初始化网页,我必须通过它们的类名(slide
)找到一堆元素,并根据一些逻辑.我有函数 Distribute(element)
它将一个元素作为输入并进行分配.我想做这样的事情(如此处或此处:
I am initing web page via the window.onload
, I have to find bunch of elements by their class name (slide
) and redistribute them into different nodes based on some logic. I have function Distribute(element)
which takes an element as input and does the distribution. I want to do something like this (as outlined for example here or here):
var slides = getElementsByClassName("slide");
for(var i = 0; i < slides.length; i++)
{
Distribute(slides[i]);
}
然而这对我来说并没有魔法,因为 getElementsByClassName
实际上并不返回数组,而是一个 NodeList
,即...
however this does not do the magic for me, because getElementsByClassName
does not actually return array, but a NodeList
, which is...
...这是我的推测...
...在函数 Distribute
内部被改变(DOM 树在这个函数内部被改变,并且会发生某些节点的克隆).For-each
循环结构也无济于事.
...being changed inside function Distribute
(the DOM tree is being changed inside this function, and cloning of certain nodes happen). For-each
loop structure does not help either.
变量 slides 的行为确实是不确定的,通过每次迭代它都会疯狂地改变它的长度和元素的顺序.
The variable slides act's really un-deterministicaly, through every iteration it changes it's length and order of elements wildly.
在我的情况下,迭代 NodeList 的正确方法是什么?我正在考虑填充一些临时数组,但不知道该怎么做...
What is the correct way to iterate through NodeList in my case? I was thinking about filling some temporary array, but am not sure how to do that...
我忘记提及的重要事实是另一张幻灯片中可能有一张幻灯片,这实际上是更改 slides
变量的原因,因为我刚刚发现感谢用户 Alohci.
important fact I forgot to mention is that there might be one slide inside another, this is actually what changes the slides
variable as I have just found out thanks to user Alohci.
我的解决方案是先将每个元素克隆到一个数组中,然后将数组一个一个地传递给 Distribute()
.
The solution for me was to clone each element into an array first and pass the array ono-by-one into Distribute()
afterwards.
推荐答案
根据 MDN,从 NodeList
检索项目的方法是:
According to MDN, the way to retrieve an item from a NodeList
is:
nodeItem = nodeList.item(index)
因此:
var slides = document.getElementsByClassName("slide");
for (var i = 0; i < slides.length; i++) {
Distribute(slides.item(i));
}
我自己还没有尝试过(正常的 for
循环一直对我有用),但试一试.
I haven't tried this myself (the normal for
loop has always worked for me), but give it a shot.
这篇关于如何正确迭代 getElementsByClassName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!