0

I want to pass current iteration of foreach loop on click event, yet it returns "undefined" - but why?

for (var i = 0; i < __ARR_selectors.length; i++) {
    __ARR_selectors[i].click( function(e, i) {
        console.log(i); //returns undefined
}

1 Answer 1

2

Try this:

for (var i = 0; i < __ARR_selectors.length; i++) {
    (function (i) {
        __ARR_selectors[i].click( function() {
            console.log(i); //returns undefined
        });
    })(i);
}

The problem with your code is the variable i is updated for each iteration of the loop, so the click event gets bound to the last value that i had.

To get round the issue, create an anonymous function which accepts a parameter of i which gets round javascript closures.

Sign up to request clarification or add additional context in comments.

2 Comments

It's so stupid. If I console.log() it outside an click function it in the scope - wtf?
@Ultra - it's not stupid - it's design. try searching on google for articles about javascript closure - it'll make so much more sense when you understand it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.