javascript 将变量传递给回调函数的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6425799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
the right way to pass variable to a callback function
提问by ilyo
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?
但是我想要一个命名的回调函数,我someVar
是否正确地调用了传递的函数?
$('#div').click(someFunction(someVar));
function someFunction(someVar){}
回答by SLaks
Both of your examples are wrong.
你的两个例子都是错误的。
Your first example creates a parameterto the callback method named someVar
; it will become the event
object that jQuery passes to the handler method.
您的第一个示例为名为;的回调方法创建了一个参数someVar
。它将成为event
jQuery 传递给处理程序方法的对象。
The second example calls the method immediately, then passes its resultto the click
method as an event handler.
第二个示例立即调用该方法,然后将其结果click
作为事件处理程序传递给该方法。
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); });
回答by Alnitak
The click
callback function will be passed a jQuery Event object, not someVar
.
该click
回调函数将被传递一个jQuery事件对象,而不是someVar
。
You have to call your function yourself withinthe 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
}
回答by FishBasketGordo
Look into passing the arguments as event data to the click event (or any event with jQuery): http://api.jquery.com/click/
查看将参数作为事件数据传递给点击事件(或任何带有 jQuery 的事件):http: //api.jquery.com/click/