Assign click handlers in for loop
It's a common mistake to create closures in loops in Javascript. You need to have some sort of callback function like this:
function createCallback( i ){ return function(){ alert('you clicked' + i); }}$(document).ready(function(){ for(var i = 0; i < 20; i++) { $('#question' + i).click( createCallback( i ) ); }});
Update June 3, 2016: since this question is still getting some traction and ES6 is getting popular as well, I would suggest a modern solution. If you write ES6, you can use the let
keyword, which makes the i
variable local to the loop instead of global:
for(let i = 0; i < 20; i++) { $('#question' + i).click( function(){ alert('you clicked ' + i); });}
It's shorter and easier to understand.
To clarify, i is equal to 20 because the click event won't have fired until after the loop has finished.
$(document).ready(function(){ for(var i = 0; i < 5; i++) { var $li= $('<li>' + i +'</li>'); (function(i) { $li.click( function(){ alert('you clicked ' + i); }); }(i)); $('#ul').append($li); }});