I wanted to solve this question posted as a public question on testdome. Each as[i]
should be a function that does alert(i)
.
The code to be bug-fixed is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (i = as.length; i-- >= 0;) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}
The solution I attempted is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
//made the loop variables more explicit
for (i = as.length-1; i >=0; i--) {
var x = i;
as[x].onclick = function() {
alert(x);
return false;
}
}
}
I though that variable i
is persistent, so I kept its copy in variable x, and use variable x
instead of i
. But it does not solve the problem completely. Please let me know what is my misunderstanding.