从getElementsByClassName遍历HTMLCollection时的奇怪行为 [英] Strange behavior when iterating over HTMLCollection from getElementsByClassName

查看:446
本文介绍了从getElementsByClassName遍历HTMLCollection时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数来更改元素的类以更改其属性.由于某些原因,只有某些元素发生了变化.我花了几个小时才找到解决方案,但对我来说似乎很奇怪.也许你可以向我解释一下.

I wrote a function to change the class of elements to change their properties. For some reason, only some of the elements have changed. It took me a few hours to find a solution, but it seems odd to me. Perhaps you can explain this to me.

这不起作用:

function replace(){
  var elements = document.getElementsByClassName('classOne');

  for (var i = 0; i < elements.length; i++) {
    elements[i].className = 'classTwo';               
  }
}

参见JSFiddle :仅第二个项目受到影响;只有每隔一秒的红色元素就会将颜色变为蓝色.

See the JSFiddle: only every second item is affected; only every second red element changes color to blue.

所以我将for循环的最终表达式更改为不再增加i:

So I changed the final expression of the for loop to not increment i anymore:

function replace(){
  var elements = document.getElementsByClassName('classOne');

  for (var i = 0; i < elements.length; i) { // Here’s the difference
    elements[i].className = 'classTwo';               
  }
}

这很好!好像push被调用,不需要增量.这正常吗?它与我所看到的示例不同.

This works well! It seems as though push is called and no increment is needed. Is this normal? It is different from the examples I’ve seen.

推荐答案

正在发生的事情是一个奇怪的副作用.为elements的每个元素重新分配className时,该元素将从数组中删除! (实际上,正如@ user2428118指出的那样,elements是类似于数组的对象,而不是数组.请参见

What's going on is an odd side effect. When you reassign className for each element of elements, the element gets removed from the array! (Actually, as @ user2428118 points out, elements is an array-like object, not an array. See this thread for the difference.) This is because it no longer has the classOne class name. When your loop exits (in the second case), the elements array will be empty.

您可以将循环编写为:

while (elements.length) {
    elements[0].className = 'classTwo'; // removes elements[0] from elements!
}

在第一种情况下,通过增加i,您将跳过具有类classOne的(原始)元素的一半.

In your first case, by incrementing i, you are skipping half of the (original) elements that have class classOne.

顺便问一句很好的问题.经过精心研究和明确.

Excellent question, by the way. Well-researched and clear.

这篇关于从getElementsByClassName遍历HTMLCollection时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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