Question

Some time ago I posted a question about what questions should a good javascript coder be able to answer. Meder pointed out the following question:

The following code makes clicks on any "a" element to alert(-1) due to the fact that "i" is hold in the onclick function as a reference and not as a value:

<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>

The question is: How to fix this implementation so that the onclick function holds the value of i and not it's reference?

I don't know the answer. How to fix it? How to make i to be a copy of the reference value rather than the actual reference?

Side questions: Are all variable types passed in as a reference? Or does it vary on whether it's a primitity type or an object?

Any thoughts would be appreciated.

Was it helpful?

Solution

To understand this problem, you must learn what a closure is. Then you must also know how javascript deals with scope (it is on a function-basis rather than on a block-basis as C for example).

Here's the "stantard" solution:

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

Another version that does exactly the same thing, but might be easier to understand if you are not used to closures and scope in JS is:

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

Got the idea?

OTHER TIPS

<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() {
        return function() {
           alert(i);
           return false;
        }
    }();
}
</script>

maybe?

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