getElementsByClassName - 奇怪的行为 [英] getElementsByClassName - Strange behavior

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

问题描述

首先,抱歉我的英语不好......

First, sorry for my bad English...

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

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 he seems odd to me, perhaps you can explain to me.

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

不能正常工作,在这里演示,[在chrome 25和FF上],所以我采用了循环系数:

not working as well, Demo here, [on chrome 25 and FF], So I took the loop coefficient:

function replace(){
   var elements = document.getElementsByClassName('classOne');
   for (var i=0; i<elements.length;i) { //----here the different --- i without ++
    elements[i].className = 'classTwo';               
   }
}

这很有效!似乎是'推'被称为,并且不需要系数...
这是正常的吗?它与我见过的例子不同。

This works well! seems as 'push' called, and no coefficient needed... It is normal? It is different from the examples I've seen.

提前致谢!

推荐答案

发生了什么是奇怪的副作用。当您为元素的每个元素重新分配 className 时,该元素将从数组中删除! (实际上,正如@ user2428118指出的那样,元素是一个类似数组的对象,而不是一个数组。参见这个主题的差异。)这是因为它不再有 classOne 类名。当你的循环退出时(在第二种情况下),元素数组将为空。

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 - 奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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