Consider this code:
for( var i = 1; i <= 2; ++i )
{
$( '#id' + i ).click(
function()
{
alert( 'ID = ' + i );
}
)
}
The problem is that when id1 or id2 is clicked the alert always says ID = 3. Now I know why this happens (it is evaluated at call time), I am just curious if there is any way to prevent that? (1)
Many questions here and articles in general explain the concept of closure quite well, I have however been unable to find any technique to avoid it.
On a side note, I tried to use (note the extra keyword "new"):
new function() { alert( 'ID = ' + i ) }
however that calls the alert directly at the time it is defined and does nothing on click events. Any idea on this? (2)