Jquery each() Counter
I've done some searching around the documentation, and spent a while on the net but cannot find a solution to this! I want the alert to tell me which iteration of each() it was on when the .thumb is clicked.
EG: There are six .thumb's I click on number 3, the browser pops-up 3!
What actually happens is regardless of which .thumb is clicked, 6 pops up.
var counter = 1;
$('.thumb').each(function () {
$(this).click(function () {
开发者_如何学运维alert (counter);
});
counter++;
});
Any help is gratefully received.
That's because you're sharing the same counter
variable for all click
handlers and it is whatever it ends up being at the end of the loop. Instead, use the one passed into the loop (the index parameter of the .each()
that's already there), like this:
$('.thumb').each(function (i) {
$(this).click(function () {
alert (i+1); //index starts with 0, so add 1 if you want 1 first
});
});
You can test it here.
To use a solution like @Paulo suggested, you would need to do so like this:
var list = $('.thumb');
for(var i=0; i<list.length; i++) {
(function( i_local ) {
list.eq( i ).click(function(){
alert(i_local);
});
})( i + 1 );
}
...although I'd use @Nicks .each()
solution instead. Much cleaner.
精彩评论