问题
my javascript function is only changing two of 4 classes. If I click it again it changes the third one but then completely ignores the last one.
function move(obj,obj2) {
var _elements = document.getElementsByClassName(obj);
document.getElementsByClassName(obj2).className = 'none';
for( var i = 0; i < _elements.length; i ++){
_elements[i].className ='none';
}
}
<a href="javascript: move('bigbox','bigbox_submit');" id="closebigbox" >Clear</a>
<form>
<input type="text" class="bigbox" /><br/>
<input type="text" class="bigbox" /><br/>
<input type="text" class="bigbox" /><br/>
</form>
<a href="javascript:" class="bigbox_submit" >Submit</a>
How do I make it stop doing this and execute at the same time.
回答1:
The method document.getElementsByClassName() returns a NodeList, which is a "live" object. That is, as the DOM changes, the NodeList instance changes with it. So, each time you change the class of one of the elements in your node list, that element is then removed from the node list because it no longer matches the class. You can use a while loop instead:
var _elements = document.getElementsByClassName(obj);
while (_elements.length) {
_elements[0].className ='none';
}
The second problem is that you are assigning a property named className to a NodeList object. This will not affect any of the elements in that NodeList object. You need to set the className of the elements in the NodeList.
document.getElementsByClassName(obj2)[0].className = 'none';
回答2:
The .getElementsByClassName() method is supposed to return a NodeList (though according to MDN most browsers return an HTMLCollection), which means you need to access it like an array. So you can't directly set .className on the return and instead of:
document.getElementsByClassName(obj2).className = 'none';
You need:
var els = document.getElementsByClassName(obj2),
i;
for (i = els.length - 1; i >= 0; i--)
els[i].className = 'none';
// or if you know there will always be exactly one element returned:
document.getElementsByClassName(obj2)[0].className = 'none',
The reason I've set the loop to count down is that a NodeList is supposed to be live, so if you start modifying the elements in the list they might disappear from the list and mess up your counter.
来源:https://stackoverflow.com/questions/9087202/javascript-changes-one-some-class-names