【问题标题】:jQuery $.when with deferreds not workingjQuery $.when 延迟不起作用
【发布时间】:2011-11-30 07:55:11
【问题描述】:

我想要做的是在两个同时通过 ajax 加载的图像完成时执行一些操作。为此,我创建了一个自定义 Deferred,以便在图像加载完成时解决。

<div id="i"></div>
$(document).ready(function() {
    $('#i').hide();
    var imgLoad = loadImgs();
    $.when(imgLoad).then(function() {
        $('#i').show('slow');
    });
});

function loadImgs() {
    var dfd = $.Deferred();

    var matrix = $.getJSON("https://graph.facebook.com/thematrixmovie");
    var pulp = $.getJSON("https://graph.facebook.com/pulpfiction");

    $.when(matrix, pulp).then(function(m, p) {
        mImg = '<img src=' + m[0].picture + '>';
        pImg = '<img src=' + p[0].picture + '>';
        $('#i').show().append(mImg + pImg);
        dfd.resolve;
    });
    return dfd.promise();
}

你可以试试这个on JSFiddle。

我使用了 Eric Hynds post,包括 working example 作为参考,但仍然无法使用。有什么想法吗?

【问题讨论】:

    标签: javascript jquery jquery-deferred


    【解决方案1】:

    您正确使用了$.when,但您尝试像这样调用resolve 方法:

    dfd.resolve;
    

    与其他一些语言不同,JavaScript 不允许您在方法调用中省略括号。您只需要添加它们,您的代码就可以正常工作!

    dfd.resolve();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多