简体   繁体   中英

jquery.click(callmethod)

$('<a/>').click(function(event) { ChangeXYZ(event); });

Problem with above is i do not want event but i someother var.

$('<a/>').click(function() { ChangeXYZ(var123); });

But problem with line is, it is getting value of var123 at runtime and as i am adding this in loop so always end up using last value of var123. Looks like it is using reference for var123. How can i make it use value of var123 when this was created instead of click time.

use closures

function (val) {
    return function() {
         ChangeXYZ(val);
    }
}(var123);

note: not tested, but should work.

edit: fixed spelling

Let's say your for-loop looked like this:

for (var var123=0; var123<10; var123++) {
    $('<a/>').click(function() { ChangeXYZ(var123); });
}

Change this to:

for (var var123=0; var123<10; var123++) {
    (function() {
        $('<a/>').click(function() { ChangeXYZ(var123); });
    })();
}

Wrapping the for-loop with a closure would do the trick. In fact, if you run your program through JSLint, you'll get a warning saying "Be careful when making functions within a loop. Consider putting the function in a closure."

Is there a reason you can't put a statement staticvar123 = var123; before var123 is modified and change your code to:

$('<a/>').click(function() { ChangeXYZ(staticvar123); });

First of all, have in mind that if you attach a click event inside a loop to the the same element (in your case the element $('<a/>') ), then you'll end up responding N-times to the same event for that element. So you probably don't want this and you need to move the calling to .click out of the loop.

Second, if you still need something like this I believe @sanand0 had a mistake and you should consider passing a parameter to the caller function and using this parameter inside the function:

for (var var123=0; var123<10; var123++) {
    (function(v) {
        $('<a/>').click(function() { ChangeXYZ(v); });
    }(var123));
}

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