简体   繁体   中英

Pass custom variable to anonymous jQuery click function

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM