如何使 myFunction 对 .ready() 事件中的内联函数可见?
$(document).ready(function() {
...stuffs...
myFunction(par1, par2, anotherFucntion_callback);
}
);
function anotherFunction_callback(data) {
..stuffs..
}
如何使 myFunction 对 .ready() 事件中的内联函数可见?
$(document).ready(function() {
...stuffs...
myFunction(par1, par2, anotherFucntion_callback);
}
);
function anotherFunction_callback(data) {
..stuffs..
}
您使用函数的实际名称,即myFunction_callback
代替myFunction
or anotherFucntion_callback
。
我没完全听懂你的问题。你的意思是你想传递“myFunction_callback(data)”作为你的最后一个参数:
myFunction(par1, par2, anotherFunction_callback);
,包括那个“数据”参数?
在那种情况下,解决方案是相当标准的,在那个之前写下这个:
var temp = function() { anotherFunction_callback(data) };
另一种语法是:
function temp() { myFunction_callback(data) };
// even though this looks just like a free function,
// you still define it inside the ready(function())
// that's why I call it "alternative". They are equivalent.
通常,如果您想将带有 1 个或多个参数的函数传递给另一个函数,则使用该格式。在这里,我们基本上创建了一个新的无参数函数来调用另一个函数。新函数可以访问“数据”变量。它被称为“闭包”,您可能想了解更多。当然,如果回调不需要参数,你可以使用原来的函数名。
我希望这有帮助。
ps:您甚至可以内联函数声明,使其匿名,如下所示: myFunction(par1, par2, function() { myFunction_callback(data) }); 请注意,
$(document).ready(function() {});
看起来差不多就是这样。