Question

Why do the anchors, when clicked on, alert -1 instead of their respective counter inside of the loop? How can you fix the code so that it does alert the right number?

<a href="#">text</a><br><a href="#">link</a>
<script>
var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    as[i].onclick = function() {
        alert(i);
        return false;
    }
}
</script>
Was it helpful?

Solution

That's a closure problem: every anonymous function you define inside your loop reads the value of "i" at the end of the for loop.

You need another scope, for example calling a function that sets the onclick handler.

function add_onclick(el, i) {
    el.onclick = function() {
        alert(i);
        return false;
    }
}

var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    add_onclick(as[i],i);
}

OTHER TIPS

An alternative way to achieve the same result as Keeper's answer is to use a function expression for the closure, which you immediately invoke, using your value as a parameter to create the closure

var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) (function (i) {
    as[i].onclick = function() {
        alert(i);
        return false;
    }
}(i));

This way requires minimal code refactoring

You are printing the value of variable i. After the loop, it's value is -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top