Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each() Counter

Tags:

jquery

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.

like image 406
adamg2000 Avatar asked Oct 14 '10 01:10

adamg2000


People also ask

What is each() in jQuery?

jQuery Misc each() Method The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

What is each() in javascript?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to break the each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to loop jQuery array?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


1 Answers

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.

like image 193
Nick Craver Avatar answered Sep 21 '22 19:09

Nick Craver