Ok, here\'s a problem script.
var links = [ \'one\', \'two\', \'three\' ];
for( var i = 0; i < links.length; i++ ) {
var a = document.createElement(
I'd stay with your own solution, but modify it in the following way:
var links = [ 'one', 'two', 'three' ];
function handler() {
alert( this.i );
}
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 = handler;
document.body.appendChild( a );
}
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.