开发者

the right way to pass variable to a callback function [duplicate]

This question already has answers here: Pass an extra argument to a callback function (5 answers) Closed 6 years ago.

When I have

$('#div').click(function(someVar){//do something with soneVar});

but I want to have a named callback function, am I palcing the passed someVar correctly?

开发者_运维技巧
$('#div').click(someFunction(someVar));
function someFunction(someVar){}


Both of your examples are wrong.

Your first example creates a parameter to the callback method named someVar; it will become the event object that jQuery passes to the handler method.

The second example calls the method immediately, then passes its result to the click method as an event handler.

You you need to pass a function expression that calls your function with a parameter from the outer scope (using a closure):

$('#div').click(function() { someFunction(someVar); });


The click callback function will be passed a jQuery Event object, not someVar.

You have to call your function yourself within the callback function.

$('#div').click(function(ev) {
    someFunction(someVar);
}

function someFunction(someVar) {
     ...
}

Alternatively, do:

$('#div').click({someVar: someVar}, someFunction);

function someFunction(ev) {
    // your var is now in ev.data.someVar
}


Look into passing the arguments as event data to the click event (or any event with jQuery): http://api.jquery.com/click/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜