Ok, here\'s a problem script.
var links = [ \'one\', \'two\', \'three\' ];
for( var i = 0; i < links.length; i++ ) {
var a = document.createElement(
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:
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( arguments.callee.i ) }
a.onclick.i = i;
document.body.appendChild( a );
}
The technique is useful when your function needs to store persistent information between calls. Replace the part above with this:
a.id="div"+i;
a.onclick = function() {
var me = arguments.callee;
me.count=(me.count|0) + 1;
alert( me.i );
}
and you can later retrieve how many times it was called:
for( var i = 0; i < links.length; i++ ){
alert(document.getElementById("div"+i).onclick.count);
}
It can also be used to cache information between calls.