问题描述
以下javascript代码无法正常运行. (我使用的是IE9,不能使用其他浏览器或JQuery):
The following javascript code does not work correctly. (I am using IE9 and cannot use a different browser or JQuery):
var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {
elems[i].className = "Zero";
}
发生的事情是,只有某些具有className"EditableTextBox"的元素被更改为className"0",许多元素仍保留为className"EditableTextBox".没有其他代码可能会导致此问题.这段代码是刷新屏幕之前我执行的最后一部分代码.
What happens is, only SOME elements with className "EditableTextBox" are changed to className "Zero", many remain with className "EditableTextBox". There is no further code that could be causing this issue; this code is the last bit of code I execute before the screen is refreshed.
我认为问题出在.getElementsByClassName找不到所有正确的元素,但是:
I thought the problem was with .getElementsByClassName not finding all the correct elements, however:
var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {
elems[i].value = "test";
}
此代码确实将所有正确元素的值更改为"test",因此.getElementsByClassName确实可以找到所有元素.
This code DOES change the value of ALL the correct elements to "test", so .getElementsByClassName DOES find all the elements correctly.
我不明白是什么引起了这里的问题.下面是我的解决方法,但是在这里有更多经验的人可以解释为什么第一段代码不起作用吗?谢谢你.
I do not understand what is causing the problem here. My way around this is below, but can anyone with more experience here please explain why the first block of code is not working? Thank you.
如果有人感兴趣,我的解决方法:
My Workaround in case anyone is interested:
var elems = document.getElementsByTagName("input");
for (var i = 0; i < elems.length; i++) {
if (elems[i].className == "EditableTextBox")
elems[i].className = "Zero";
谢谢.
推荐答案
getElementsByClassName
似乎返回一个实时集合,因此,当您更改任何项目的类时,集合将立即更新,并且它将彼此跳过.相反,请执行相反的循环:
The getElementsByClassName
seems to return a live set, so when you change the class of any item the set gets updated immediately, and it will skip each other item. Do the loop in reverse instead:
for (var i = elems.length - 1; i >= 0; --i) {
elems[i].className = "Zero";
}
这篇关于更改className问题(javascript和IE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!