[英]jQuery ajax content loaded in div, event ready
我正在使用jQuery Ajax在頁面中動態加載內容。 內容包含圖像,因此我需要知道所有圖像將在何時加載,例如DOM Ready。
最初的內容將被隱藏。 圖像成功加載后,我顯示包含它們的div。 有沒有一種方法可以檢測何時可以顯示使用Ajax加載的內容? 從服務器返回文本響應時,將調用Ajax success
函數,但是在全部加載並且還加載圖像時,我需要執行一個函數。
如果您剛剛在文檔中插入了一堆HTML(包含一些<img>
標記),並且想知道何時加載所有這些新圖像,則可以這樣做。 假設動態內容全部插入了#root
對象。 在插入動態競爭之后,可以立即運行以下代碼:
function notifyWhenImagesLoaded(rootSelector, callback) {
var imageList = $(rootSelector + " img");
var imagesRemaining = imageList.length;
function checkDone() {
if (imagesRemaining === 0) {
callback()
}
}
imageList.each(function() {
// if the image is already loaded, just count it
if (this.complete) {
--imagesRemaining;
} else {
// not loaded yet, add an event handler so we get notified
// when it finishes loading
$(this).load(function() {
--imagesRemaining;
checkDone();
});
}
});
checkDone();
}
notifyWhenImagesLoaded("#root", function() {
// put your code here to run when all the images are loaded
});
插入動態內容后,可以調用此函數。 它查找動態內容中的所有圖像標簽,並檢查是否已加載任何圖像標簽。 如果有,它將計算在內。 如果還沒有,那么它將安裝一個加載事件處理程序,以便在圖像加載時得到通知。 當最后一個圖像完成加載時,它將調用回調。
阿賈克斯
$.ajax({
type: "POST",
url: "myfile.*",
data: {data : params},
cache: false,
success: function(return_data){
//here you have the answer to Ajax
//at this point you have the content ready for use
//in your case here you would find the images that you got back from the file called by ajax
}
});
您可以對負載使用on方法。 計算您總共有多少個物品,並使用load事件來加載總數量的圖像。 您甚至可以建立這樣的進度條。
這樣,在完成ajax調用之后
$('img').on('load', function(){
// Count items here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.