嗨,有人可以向我解释一下jquery回调的概念有点困在这个简单的代码上
$(document).ready(function(){
bar('',function(){
foo();
});
});
function foo()
{
alert('foo');
}
function bar()
{
alert('bar');
}
Run Code Online (Sandbox Code Playgroud)
因此,foo()首先执行bar(),但使用上面的代码,只foo()执行并且bar不执行.
这是一个jsfiddle链接
函数是JavaScript中的第一类成员,因此可以分配给变量并作为参数传递给其他函数.回调函数的思想是函数接收的一个(或多个)参数是可以在某些条件下调用的函数引用.在你的情况下,你bar用两个参数调用但从不对这些参数做任何事情bar.JavaScript不会自动回调函数,因为程序员必须这样做.
这可能是你想要的:
$(document).ready(function(){
bar('',function(){ //this anonymous function maps to the parameter b in bar(a,b)
foo(); //missing ; can lead to hard to track errors!
});
});
function foo()
{
alert('foo');
}
//accept two parameters
// in this example code, given the call to bar() above, a will map to '' and b to the anonymous function that calls foo()
function bar(a, b)
{
alert('bar');
if(typeof b === 'function'){ //check if b is a function
b(); //invoke
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
@贾里德的建议无疑更有意义-变化if(b)给if(typeof b === 'function'){调用之前b