如何正确迭代getElementsByClassName [英] How to correctly iterate through getElementsByClassName

查看:208
本文介绍了如何正确迭代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...

...这是我的猜测.. 。

...内部功能更改分发(此DOM内部正在更改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.

变量幻灯片动作真的不确定性,通过每次迭代它更改了元素的长度和顺序。

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...

重要的事实我忘了提到是可能有一个幻灯片在另一个,这其实是什么改变了幻灯片变量,因为我只是感谢用户 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));
}

我没有尝试过这个(正常的对于循环一直为我工作),但给它一个镜头。

I haven't tried this myself (the normal for loop has always worked for me), but give it a shot.

这篇关于如何正确迭代getElementsByClassName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆