Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass counter to anonymous function

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

like image 732
davidkomer Avatar asked Dec 13 '25 08:12

davidkomer


1 Answers

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

  • the scope of a variable is either a function or the global scope (never a simple block)
  • a function keeps a pointer to the scope in which it was declared and can use the variables of this scope when it's executed (this is called a closure)
like image 134
Denys Séguret Avatar answered Dec 15 '25 03:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!