tags:

views:

36

answers:

3

Hi Guys, 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.

+2  A: 

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.

Nick Craver
You're a scholar and a gentleman! Thanks for your solution.
adamg2000
A: 

The function() call is an anonymous function declaration. You have to understand how LISP functions work (yes, ecmascript is lisp).

Instead of $('.thumb').each, you should use something like (untested):

var list = $('.thumb');
for(var i=0; i<list.length; i++) {
    $(list[i]).click(function(){
        alert(i);
    });
}
Paulo Scardine
This doesn't solve the problem, it's a lot less efficient, but the same problem of a shared variable, they'll all alert what `i` was at the end of the loop.
Nick Craver
@Nick is right. This would produce the same result as in the question.
patrick dw
Ok, my bad. I should not post this without testing.
Paulo Scardine
A: 

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.

patrick dw