javascript - jQuery $.when 延迟不工作

标签 javascript jquery jquery-deferred

我想要做的是在通过 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作为引用,但仍然没有得到它的工作。有什么想法吗?

最佳答案

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

dfd.resolve;

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

dfd.resolve();

关于javascript - jQuery $.when 延迟不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8322707/

相关文章:

javascript - Vue 使用 v-for 迭代 API 响应的嵌套数组

javascript - 如何获取鼠标点击div的宽度?

jquery - 在我的移动网站上禁用输入标签的自动缩放/字段缩放 - 不禁用所有缩放功能

javascript - 为什么 iOS 的滚动事件不能使元素可见?

javascript - jsfiddle jquery ajax 没有按预期返回数据

javascript - jQuery 在悬停时打开 div;自动滚动

javascript - 当页面位置改变时调用 Tampermonkey 脚本

javascript - RNCryptor IOS + Javascript 加密/解密 AES 256

javascript - 如何从已解析的 jQuery.Deferred() 中获取值(value)?

javascript - 内部请求失败导致父请求失败