【问题标题】:JQuery deferred.done executes predefined function instantly, but not function declared insideJQuery deferred.done 立即执行预定义的函数,但不执行内部声明的函数
【发布时间】:2014-10-26 17:42:37
【问题描述】:

如标题所述,我的问题很奇怪。代码如下:

案例一:

    var first = $.ajax({ // about 500ms request
        url: myUrl
        success: function() { console.log(1); }
    });

    var second = $.ajax({ // about 200 ms request
        url: myUrl
        success: function() { console.log(2); }
    });


    $.when(first, second).done(function() { console.log(3); });

记录 2、1、3。一切都很好,正是我想要的。

案例 2:

    var first = $.ajax({ // about 500ms request
        url: myUrl
        success: function() { console.log(1); }
    });

    var second = $.ajax({ // about 200 ms request
        url: myUrl
        success: function() { console.log(2); }
    });

    function logthree() {
        console.log(3);
    }


    $.when(first, second).done(logthree());

日志 3、2、1,这是一个问题。 logthree() 函数应该只在第一次和第二次解析时执行一次。

为什么会这样?我怎样才能在没有任何问题的情况下使用案例 2?

注意:如果 first 和 second 是函数并且它们返回 $.ajax,则会发生同样的情况。

注意:如果 first 和 second 都是 $.get,则会发生同样的事情。

【问题讨论】:

    标签: jquery ajax .when


    【解决方案1】:

    改为:

    $.when(first, second).done(logthree);
    

    您正在执行logthree() 并将返回结果传递给.done()。您需要将函数引用传递给.done(),它只是没有括号的logthree。当您添加括号时,它会指示 JS 解释器立即执行它。这是一个常见的错误。

    【讨论】:

      【解决方案2】:

      试试这个..

      `$.when(first, second).done(logthree);

      【讨论】:

      • 谢谢,它有效! (将接受 jfriend00 的解释来解释。)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2020-12-08
      • 2011-10-04
      相关资源
      最近更新 更多