adamg2000
adamg2000

Reputation: 543

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.

Upvotes: 44

Views: 84303

Answers (2)

user113716
user113716

Reputation: 322492

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.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

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.

Upvotes: 77

Related Questions