Kindof a basic question, but how do I pass a distinct value to an anonymous function?
Maybe there's a better way of phrasing this... what I mean is, consider the following code... assuming I have a bunch of clickable items with ids like somediv1, somediv2, etc.
for(idx = 1; idx < 30; idx++) {
$("#somediv" + idx).on('click', function() {foo(idx); });
}
function foo(inIDX) {
alert(inIDX);
}
No matter which div I click, it always alerts 30. I'd like clicking somediv1 to alert 1, somediv2 to alert 2, and so on
When the callback is called idx has the value of end of loop.
Here's a standard solution :
for(idx = 1; idx < 30; idx++) {
(function(i){
$("#somediv" + idx).on('click', function() {foo(i); });
})(idx);
}
The intermediate function, which is called immediately, stores the value of idx at time of execution of the loop.
Maybe I could make it clearer by remembering that in JavaScript
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