为什么和什么时候循环忽略一些项目与HTML收集 [英] Why and when for loop ignore some item with html collection
问题描述
我附上了一个codepen示例: http://codepen.io/anon/pen/zpmjJ
我只是尝试改变一个经典循环的html集合数组的类名,经过多次测试,我无法弄清楚什么是错误的,如果我做了一个共同点
< div class =test> 1< / div>
< div class =test> 2< / div>
< div class =test> 3< / div>
bout.addEventListener(click,function(){
var newtest = document.getElementsByClassName('test');
for(i = 0; i< newtest.length; i ++)
{
newtest [i] .className =bob;
}
});
这里的问题是您正在使用 document.getElementsByClassName
它给你一个 活NodeList 。您应该使用 document.querySelectorAll('。test')
来代替。
var newtest = document.querySelectorAll('。test');
for(var i = 0; i< newtest.length; i ++){
newtest [i] .className =bob;
$ b 使用活动的NodeList集合 newtest
是对动态更新的元素集合的引用(由className test
>索引)。所以在第一次循环迭代之后,当用 bob
覆盖className时,整个集合变小了(因为 newtest [0]
不再有类 test
)。它使索引转移。
另外一个问题是:不要忘记 var
关键字。
演示: http://codepen.io/anon/pen / BAFyb
I attached a codepen example : http://codepen.io/anon/pen/zpmjJ
I just try to change the classname of an html collection array with a classic loop and after many test i can't figure out whats wrong and if i made a common mistake, i have always one item ignored.
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
bout.addEventListener("click",function(){
var newtest = document.getElementsByClassName('test');
for (i=0; i < newtest.length; i++)
{
newtest[i].className="bob";
}
});
解决方案 The problem here is that you are using document.getElementsByClassName
which gives you a live NodeList. You should use document.querySelectorAll('.test')
instead.
var newtest = document.querySelectorAll('.test');
for (var i=0; i < newtest.length; i++) {
newtest[i].className = "bob";
}
With live NodeList collection newtest
is a reference to a dynamically updated collection of elements (indexed by className test
). So after the first loop iteration when you overwrite className with bob
the whole collection becomes smaller by one (because newtest[0]
no longer has class test
). It makes indices shift.
One more problem with your code: don't forget var
keywords.
Demo: http://codepen.io/anon/pen/BAFyb
这篇关于为什么和什么时候循环忽略一些项目与HTML收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!