JavaScript HtmlCollection循环永远不会返回第二个元素 [英] JavaScript HtmlCollection loop never returns second element

查看:356
本文介绍了JavaScript HtmlCollection循环永远不会返回第二个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关如何访问和迭代HtmlCollection的答案,但它在这里对我不起作用:

我得到了一些带有tabSheetActive类的元素,金额这些可以是1或更多。

我用以下方式访问它们:

i know there are answers on how to access and iterate over a HtmlCollection, but it just doesn't work for me here:
I got some elements with the class "tabSheetActive", the amount of these can be 1 or more.
I access them with:

var activeTabSheets = document.getElementsByClassName('tabSheetActive');
console.log('Active sheets amount: ' + activeTabSheets.length); // outputs 2

记录集合输出如下:

[div.tabSheetActive.sheet_512_0, div.tabSheetActive.sheet_512_0]

之后我尝试迭代它们并像这样操纵它们的类:

After that i try to iterate over them and manipulate their classes like this:

for (var i = 0; i < activeTabSheets.length; i++) { // just iterates one time
    var activeTabSheet = activeTabSheets[i];
    console.log("Index: " + i); // outputs 0 
    console.log(activeTabSheet); // outputs first element
    var newClassName = activeTabSheet.className.replace('tabSheetActive', 'tabSheet');
    activeTabSheet.className = newClassName;
}

[]。forEach.call的技巧( activeTabSheets,function(activeTabSheet){// code here}); 对我来说都不起作用。它只迭代一次。

它一定是非常愚蠢的东西,但是我一直在调试并将头发撕掉几个小时。

The tricks with [].forEach.call(activeTabSheets, function(activeTabSheet) { //code here }); don't work either for me. It just iterates once.
It must be something really stupid but i have been debugging and ripping my hair out over this for hours.

推荐答案

getElementsByClassName 返回实时 HTMLCollection。

getElementsByClassName returns a live HTMLCollection.

这一行:

activeTabSheet.className.replace('tabSheetActive', 'tabSheet');

阻止列表中的第一项成为班级成员。因此它被移除并且其他所有内容都被移除(因此索引1处的元素移动到索引0)。

Stops the first item in the list from being a member of the class. Consequently it is removed and everything else is shuffled down (so the element that was at index 1 moves to index 0).

要处理这个问题,您可以:

To deal with this you can:


  • 使用 querySelectorAll 返回非live NodeList

  • 循环HTMLCollection 向后

  • 使用循环,测试HTMLCollection的长度,并始终修改索引 0

  • 全部复制在循环之前将值放入数组

  • Use querySelectorAll which returns a non-live NodeList
  • Loop over the HTMLCollection backwards
  • Use a while loop, test the length of the HTMLCollection, and always modify index 0.
  • Copy all the values into an array before looping over that

这篇关于JavaScript HtmlCollection循环永远不会返回第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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