2011-11-30 123 views
3

我想要做的是做一些行動發生時,通過Ajax兩個同時圖像加載完成。爲此,我創建了一個自定義延遲,以在圖像加載完成時解析。

<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作爲參考,但仍然沒有得到它的工作。有任何想法嗎?

回答

3

你正確使用$.when,但你嘗試調用resolve方法是這樣的:

dfd.resolve; 

不像一些其他的語言,JavaScript並不允許你省略括號的方法調用。你只需要添加它們,你的代碼就能正常工作!

dfd.resolve();