【问题标题】:jquery callbackjQuery回调
【发布时间】:2011-04-25 02:52:35
【问题描述】:

你好,谁能给我解释一下jquery回调的概念 有点卡在这个简单的代码上

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

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

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

这样foo() 先被执行然后bar(),但是使用上面的代码,只有foo() 被执行而bar 不被执行。

这是jsfiddle link

【问题讨论】:

标签: jquery callback


【解决方案1】:

函数是 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'){

【讨论】:

  • 按顺序排列它们会破坏我学习回调的目的,我的foo()bar() 函数有回调方法吗?
  • 对,那是在您更改代码之前,我正在编辑我的答案以回复您编辑的问题。
  • @no.good.at.coding - if (typeof b == 'function') 怎么样?
  • 似乎正在工作,但有点不对劲,因为我认为回调将被放置在队列中,当父函数完成时,队列中的下一个函数将被执行,就像@987654321 中的示例一样@,但我想我可能错了
  • @ianace - 这不会自动发生,开发人员需要确保它是这样工作的。例如,jQuery 的 ready() 函数采用回调函数。如果您深入了解source for jQuery,您会发现每次将回调函数附加到ready 时,它都会被放入一个数组中。当 ready 事件触发时,回调数组中的每个条目都会被一一调用——jQuery 开发人员不得不这样编写它,JavaScript 只提供了使这种设计模式成为可能的机制。
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 2012-02-15
  • 2011-07-17
  • 2010-12-20
  • 1970-01-01
相关资源
最近更新 更多