Ok, here's a problem script.
var links = [ 'one', 'two', 'three' ];
for( var i = 0; i < links.length; i++ ) {
var a = document.createElement( 'div' );
a.innerHTML = links[i];
a.onclick = function() { alert( i ) }
document.body.appendChild( a );
}
This script generates three divs: one, two and three, using an array.
I've set a (Dom0 for simplicity) click handler on each div which alerts the index of its position in the array. - except it doesn't! It always alerts 3, the last index of the array.
This is because the 'i' in 'alert( i )' is a live reference to the outer scope (in this case global) and its value is 3 at the end of the loop.
What it needs is a way of de-referencing i within the loop.
This is one solution and I tend to use it.
var links = [ 'one', 'two', 'three' ];
for( var i = 0; i < links.length; i++ ) {
var a = document.createElement( 'div' );
a.innerHTML = links[i];
a.i = i; //set a property of the current element with the current value of i
a.onclick = function() { alert( this.i ) }
document.body.appendChild( a );
}
Does anyone else do anything different?
Is there a really smart way of doing it?
Does anyone know how the libraries do this?
You need to use this little closure trick - create and execute a function that returns your event handler function.
I'd stay with your own solution, but modify it in the following way:
This way, only one function object gets created - otherwise, the function literal will be evaluated on every iteration step!
A solution via closure is even worse performance-wise than your original code.
I recommend Christophs way with one function since it uses less resources.
Below is another way that stores the value on the function (that is possible because a function is an object) and users argument.callee to get a reference to the function inside the function. In this case it doesn't make much sense, but I show the technique since it can be useful in other ways:
The technique is useful when your function needs to store persistent information between calls. Replace the part above with this:
and you can later retrieve how many times it was called:
It can also be used to cache information between calls.
RoBorg's method is definitely the way to go, but I like a slightly different syntax. Both accomplish the same thing of creating a closure that preserves 'i', this syntax is just clearer to me and requires less modification of your existing code:
var links = [ 'one', 'two', 'three' ];