简体   繁体   English

更改className问题(javascript和IE)

[英]changing className issue (javascript and IE)

The following javascript code does not work correctly. 以下javascript代码无法正常运行。 (I am using IE9 and cannot use a different browser or JQuery): (我使用的是IE9,不能使用其他浏览器或JQuery):

var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {                
    elems[i].className = "Zero";
}

What happens is, only SOME elements with className "EditableTextBox" are changed to className "Zero", many remain with className "EditableTextBox". 发生的情况是,只有某些具有className“ EditableTextBox”的元素被更改为className“ 0”,许多元素仍保留为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. 此代码是刷新屏幕之前我执行的代码的最后一部分。

I thought the problem was with .getElementsByClassName not finding all the correct elements, however: 我认为问题出在.getElementsByClassName找不到所有正确的元素,但是:

var elems = document.getElementsByClassName("EditableTextBox");
for (var i = 0; i < elems.length; i++) {                
    elems[i].value = "test";
}

This code DOES change the value of ALL the correct elements to "test", so .getElementsByClassName DOES find all the elements correctly. 这段代码确实将所有正确元素的值更改为“ test”,因此.getElementsByClassName确实可以正确找到所有元素。

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";

Thank you. 谢谢。

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. getElementsByClassName似乎返回一个活动集,因此,当您更改任何项目的类时,该集将立即更新,并且它将彼此跳过。 Do the loop in reverse instead: 反向执行循环:

for (var i = elems.length - 1; i >= 0; --i) {                
    elems[i].className = "Zero";
}

An alternative would be: 一种替代方法是:

while(list.length!=0) {
    list[0].className = 'Zero';
}

That way you know you can't miss an element. 这样,您就知道您不会错过任何元素。

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

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