Hi all,
I am sucking with this problem over 4 hours and couldn't find an answer. Here is the code:
Code:
var inputCheck = document.getElementsByTagName("input");
for( i = 0; i < inputCheck.length; i++) {
inputCheck[i].onclick = function() {
inputCheck[i].setAttribute('select', 'ok');
}
}
When I run this code I get an error: TypeError: inputCheck[i] is undefined.
I don't know because, the variable i that I defined in for loops is in global scope, so I think the anonymous function that is attached to onclick event CAN access it.
However, I got that error on firebug.
Could someone help me point out what's wrong in this situation?
Thank you!
it's called function closure. Basically, when the click happens, the loop has finished running, and i has the value of inputCheck.length, and there is no element which relates to inputCheck[inputCheck.length].
And even if there were, it wouldn't be the one you were trying to access.
Have a look here, at the section titled "The Infamous Loop Problem"
Bookmarks