This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this questionFollowing code is causing 开发者_JAVA百科the problem:
var CheckBoxes = document.getElementsByClassName('DeleteCheckBox')
for (var i = 0; i < CheckBoxes.length; i++) {
CheckBoxes[i].checked = false;
}
Well, the checkboxes are still selected after this runs. And it runs, because I checked the i variable and it is counting.
What is wrong here? By the way, only checkboxes have the "DeleteCheckBox" class, so only checkboxes get returned by getElementsByClassName.
SOLVED:
I've found the problem. I am using asp.net and the framework seems to assign the class to the "label" (it creates a span tag) of the checkbox, not to the input.
Fixed with InputAttributes.Add("class", "DeleteCheckBox"); (asp.net codebehind)
Your code is perfectly fine. On the webpage, right click and check the source. If you don't see <input type="checkbox" class="DeleteCheckBox" ...>
then you are looking at the wrong place. Your JS code assumes that the class DeleteCheckBox is applied to the checkboxes. Fix your markup.
Well if you had copy pasted the code : ';' is missing on - suggest you use to console.log to check where problem lies [whether the code infact runs or are their errors while selecting].
I'm taking a stab at this, as I don't have time to write a full demo. getElementsByClassName creates something called a HTMLcollection. HTML collections are live lists, which means everytime you access them they rerun the query that you used to generate the collection.
Everytime you update the checked property the getElementsByClassName is run and a new collection is generated. So if there were 10 input boxes, you remove one with this class there are now 9, and the variable updates to 9. If you change this to getElementsByTagName('input') this method will work, because when the query is rerun nothing changes. However, you probably don't want to hit every input on the page. Also, the performance will still be awful due to the way you structured your loop.
Read more here https://developer.mozilla.org/en/DOM/HTMLCollection
Here's how to refactor and make this run 1000% faster and it should 'work' as you are expecting
var inputs = document.getElementsByClassName('DeleteCheckBox'),
l = inputs.length;
while( l-- ) {
inputs[ l ].checked = false;
}
On each iteration the inputs variable will get updated to a new number, but since you are counting down this should be fine.
精彩评论