ChrisRockGM
ChrisRockGM

Reputation: 438

Why does a variable only pass the first value of a for loop in jQuery?

The value of ident changes at the first comment like it should, but at the second comment (in the jQuery function) ident always displays the value stored at arr[0]['ident'].

Code:

for (i=0;i<arr.length;i++)
{
    var ident = arr[i]['ident'];
    console.log(ident+' ');
    $(document).on('click','#'+ident, function() {
        console.log('over'+ident+' ');
    });
}

Upvotes: 1

Views: 45

Answers (1)

user229044
user229044

Reputation: 239452

JavaScript has function scope, not block scope. You can use var ident inside the loop, but that doesn't mean you're actually creating a new variable ident; there will only be one ident inside your function. All functions created/bound inside of your loop share the same reference to that single ident variable.

By the time any of your event handlers run, ident has been repeated reset to a new value, until the final iteration when it will be set to arr[arr.length - 1]['ident']. Every event handling function will have that same value for ident, because they all share a reference to the same ident variable.

To fix this, you need to pass each function its own variable to close over, typically done with an IIFE:

for (i=0;i<arr.length;i++)
{
    (function (ident) {
      console.log(ident+' ');
      $(document).on('click','#'+ident, function() {
          console.log('over'+ident+' ');
      });
    })(arr[i]['ident']);
}

Upvotes: 2

Related Questions