jQuery回调函数

3

嗨,能否有人解释一下jQuery回调的概念?我在这段简单的代码上卡住了。

$(document).ready(function(){
    bar('',function(){
        foo();
    });         
});

function foo()
{
    alert('foo');
}

function bar()
{
    alert('bar');
}

为了让foo()bar()之前执行,但是使用上面的代码时,只有foo()被执行,bar()没有被执行。

这里是一个jsfiddle链接


1
在你的示例中,只有bar()被执行。 - Andrew Whitaker
@andre whiteaker - 我正在实现jQuery教程中的某些内容 http://docs.jquery.com/How_jQuery_Works#Callback_and_Functions - ianace
1个回答

8
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
    }
}

编辑

@Jared的建议更为合理 - 在调用b之前将if(b)更改为if(typeof b ==='function'){


没错,那是在你修改代码之前的内容,我正在编辑我的回答以回应你修改后的问题。 - no.good.at.coding
2
@no.good.at.coding - 如果是 if (typeof b == 'function') 呢? - Jared Farrish
@Jared 谢谢你 - 这确实是一个更好的检查! - no.good.at.coding
2
@ianace - 这不会自动发生,开发人员需要确保它是如何工作的。例如,jQuery的ready()函数需要一个回调函数。如果你深入研究jQuery的源代码,你会发现每次将回调函数附加到ready时,它都会被放入一个数组中。当准备好的事件触发时,该回调数组中的每个条目都会依次被调用- jQuery开发人员必须以这种方式编写它,JavaScript只提供了这种设计模式可能的机制。 - no.good.at.coding
@ianace - 为了让它被解释,必须调用它。请参考:http://docs.jquery.com/Plugins/Authoring#Plugin_Methods - Jared Farrish
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接