迭代(for)在JS中奇怪地工作

时间:2016-12-12 12:18:55

标签: javascript

我有一个看似愚蠢的问题,但由于我对JavaScript不是很了解,我需要一些帮助。

我只是想迭代一个数组,但它似乎无缘无故地跳过元素。我的功能非常简单:

function uncolour(classname)
{
    var anchors = document.getElementsByClassName(classname);
    for(var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        anchor.classList.toggle("nocolor");
    }
}

问题是它一直在跳过一个元素。它适用于第一个元素,然后适用于第三个元素,依此类推。我已验证并且所有正确的元素存在于anchors数组中,但它仅在偶数索引上切换类。有什么想法吗?我在这里不知所措。

编辑:感谢您的回复。我已经阅读了其他类似的帖子,但我的情况是切换“nocolor”类不应该影响数组的元素,因为我正在寻找的类名与“nocolor”不同。我认为虽然元素可能保持不变,但它们在某种程度上是后缀,因为我已经更改了文档中元素的类。所以,我不知道为什么,但这对我有用:for(var i = anchors.length-1; i>=0; i--)

1 个答案:

答案 0 :(得分:1)

以下是您可以做的事情:

<html>
    <head>
        <script>
            window.onload = function(){
                //This gets all anchors.test.. for now
                var anchors = document.getElementsByClassName('test');
                for(var i=0; i < anchors.length; i++){
                    var anchor = anchors[i];

                    /*
                        As soon as the class test gets removed, the anchors list is updated and the .length of it adjusted.
                        This leads to the mentioned behavior of each second element being skipped

                        Turn one: a, b, c, d, e, f
                        Turn two: b, c, d, e, f
                        Turn three: b, d, e, f
                        .. As much as i is increaded the length is decreased
                    */
                    anchor.classList.toggle('test');
                    anchor.style.color = 'red'
                }
            }
        </script>
    </head>

    <body>
        <a class = 'test'>a</a><a class = 'test'>b</a><a class = 'test'>c</a><a class = 'test'>d</a><a class = 'test'>e</a><a class = 'test'>f</a>
    </body>
</html>

这是你应该做的:

<html>
    <head>
        <script>
            window.onload = function(){
                //This gets all anchors.test.. for now
                var anchors = document.getElementsByClassName('test');

                //Instead from counting up.. it gets counted down which makes the removed element irrelevant
                for(var i=anchors.length-1; i>=0; i--){
                    var anchor = anchors[i];
                    anchor.classList.toggle('test');
                    anchor.style.color = 'orange'
                }
            }
        </script>
    </head>

    <body>
        <a class = 'test'>a</a><a class = 'test'>b</a><a class = 'test'>c</a><a class = 'test'>d</a><a class = 'test'>e</a><a class = 'test'>f</a>
    </body>
</html>