简体   繁体   English

为什么这个for()循环不起作用?

[英]why this for()loop isn't working?

I have multiple elements with same class name. 我有多个具有相同类名的元素。

And I'm trying to change every elements' class name at once. 而我正试图立刻改变每个元素的类名。

So I tried this js sentences. 所以我尝试了这个js句子。

function chngeClass2(from, to){  //chngeClass() is change class name of an element, using its id.
    var before;
    before = document.getElementsByClassName(from);
    for(i=0,len=before.length ; i<len ; i++){
        before[i].className = to;
    }
}

chngeClass2('test', 'test_ani');

But it isn't working. 但它没有用。

I don't know why. 我不知道为什么。

Why this code is not working? 为什么这段代码不起作用? What is the problem? 问题是什么?

The getElementsByClassName() function returns a live list of DOM nodes. getElementsByClassName()函数返回DOM节点的实时列表。 That it's "live" means that as you change the elements involved, the list changes. 它是“实时”意味着当您更改所涉及的元素时,列表会更改。 When you change the class of an element, it's no longer in the list! 当您更改元素的类时,它不再在列表中!

You can deal with that issue by either copying the node list into a plain array before you alter any elements, or simply iterate with a while loop until the list is empty, just looking at the first element on each iteration: 您可以通过在更改任何元素之前将节点列表复制到普通数组中,或者只是使用while循环迭代直到列表为空来处理该问题,只需查看每次迭代的第一个元素:

var before = document.getElementsByClassName(from);
while (before.length)
  before[0].className = to;

You'd also probably want to add a test to make sure that "to" isn't a string that includes the class "from", or else the loop will never terminate. 您可能还想添加一个测试,以确保“to”不是包含“from”类的字符串,否则循环将永远不会终止。 In fact, because in the general case of a function like yours it'd be hard to figure out whether there'd be an infinite loop, it might be easier to do the array copy approach: 事实上,因为在像你这样的函数的一般情况下,很难弄清楚是否存在无限循环,所以可能更容易进行数组复制方法:

var before = document.getElementsByClassName(from);
before = [].slice.call(before, 0);
for (var i = 0; i < before.length; ++i)
  before[i].className = to;

When you change the class name, the element there is not exist any more, assume that you have 4 element with that class, so when you change the first class, you have 3 class and when you change the second class, 2 class are remained but the loop is in 3th call and is reached to before[2] , it cause an error, because it look for 3th element but you have only 2 element after first and second changes. 当您更改类名时,该元素不再存在,假设您有4个元素与该类,所以当您更改第一个类时,您有3个类,当您更改第二个类时,剩下2个类但循环在第3次调用并且到达before[2] ,它会导致错误,因为它查找第3个元素,但在第一次和第二次更改后只有2个元素。

Use this: 用这个:

    function chngeClass2(from, to){
    var before;
    before = document.getElementsByClassName(from);
    for(i=0,j=before.length ; i<j ; i++){
        before[0].className = to;
    }
}
chngeClass2('test', 'test_ani');

Check JSFiddle Demo 检查JSFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM