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.
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.
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.
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.
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.
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.
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