2011-12-23 65 views
1

我在每次迭代中下載圖像。所以邏輯&代碼在每個下載圖像的迭代器中都有。我希望當所有圖像下載完成後,立即我想調用一個函數,通知用戶所有圖像下載完成。 請指導我修改我現有的代碼。當所有圖像下載完成時觸發一個功能

這裏是我的代碼

$(document).ready(function() { 
$("table[id*=dgImages] img").each(function() { 
if($(this).offset().top > $(window).scrollTop() && $(this).offset().top < $(window).scrollTop() + $(window).height()) { 


$(this).attr("src", $(this).attr("original")); 
$(this).removeAttr("original"); 
} 
}); 
}); 

回答

1

的jQuery推遲對象救援:

var def = [];     // an array to store deferred objects 

$('img').each(function() {  // for each image 
    var d = $.Deferred();  // create a new deferred object 
    def.push(d);    // store it in the array for later 
    $(this).load(d.resolve); // and on load, "resolve" it 
}); 

$.when.apply($, def)   // $.when(def[0], def[1], ...); 
.then(function() {    // are all resolved, then 
    alert("all loaded!");  // do your stuff here 
}); 
+0

我有一個關於代碼ü給一點混亂。 $ .Deferred()將存儲在d中? d.resolve會返回圖像路徑或任何不同的東西? $ .when.apply($,def).then(函數()會自動調用所有圖像下載?我的要求是這樣的假設我有100個圖像下載,但我只下載10個圖像,當用戶向下滾動然後下一個所以我需要知道,當10個圖像下載完成了100,然後when.apply()會發射或沒有?請詳細討論.... merry chrismas&謝謝 – 2011-12-23 11:50:02

+0

@ user750398您可能需要閱讀http://api.jquery.com/category/deferred-object/以瞭解延遲對象是如何工作的。re:一次只有10個 - 這是一個很難解決的問題。 – Alnitak 2011-12-23 11:55:06

相關問題