views:

190

answers:

4

$('').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.

+1  A: 

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); });
Oliver N.
The format mamu used would create the anchor tag rather than just search for anchor tags.
Charles
@Charles I removed that last line not understanding your comment. Should I add it back in?
Oliver N.
+5  A: 

use closures

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

note: not tested, but should work.

edit: fixed spelling

Jonathan Fingland
+2  A: 

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."

A: 

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));
}
Protron