I'm having several div's #mydiv1
, #mydiv2
, #mydiv3
, ... and want to assign click handlers to them:
$(document).ready(function(){ for(var i = 0; i < 20; i++) { $('#question' + i).click( function(){ alert('you clicked ' + i); }); } });
But instead of showing 'you clicked 3'
when click on #mydiv3
(as for every other click) I get 'you clicked 20'
. What am I doing wrong?
You actually can attach event listeners in a for loop # As you can see from this example, an event listener is successfully attached to each button, and the console is logged each time one of them is clicked.
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With