2012-05-09 57 views
1

我需要如何來解決這個周圍的一些建議。的jQuery:如何檢查是否圖像已完成加載阿賈克斯

我有一個Ajax代碼被點擊我的頁面中的鏈接時執行。 Ajax代碼是調用PHP代碼查詢某個目錄內的圖像(縮略圖大小)的文件名。一旦執行,AJAX數據將會有我在該目錄中的縮略圖的文件名,並動態地顯示在我的網頁縮略圖。

我想知道的任何建議如何檢查是否所有縮略圖都已經裝載完畢,而無需使用的setTimeout()?並在所有縮略圖加載後執行一些jQuery代碼。我需要加載縮略圖,以便我可以設置縮略圖div的大小進行滾動。

回答

0

方法:

function imagesLoaded(imgAr, callback){ 
    var 
     // This is a copy of the array of images 
     imageAr = imgAr.slice(0), 
     // This holds the javascript Image Objects 
     images = [], 
     // This is the number of Images that has loaded 
     loadedCount = 0; 

    var imageLoaded = function(){ 
     // An image has finished loading, so increment the number of images loaded by 1 
     loadedCount++; 
     if(loadedCount>=imageAr.length){ 
      // If all images have finished loading, run the 'callback' function, to report back that images have all loaded 
      callback.call(); 
     } 
    } 

    // Loop around each image url 
    for(var i=0;i<imageAr.length;i++){ 
     // For each image, create a new object 
     images[i] = new Image(); 
     // when the image finishes loading, call the imageLoaded function 
     images[i].onload = imageLoaded; 
     // Assign the image the appropriate src attribute 
     images[i].src = imageAr[i]; 
    } 
} 

用途:

var imageAr = ['a.jpg', 'b.jpg', 'c.jpg']; 

imagesLoaded(imageAr, function(){ 
    alert('Images loaded!'); 
}); 
+0

HI jeztems,對不起我的無知。這是什麼目的? 「callback.apply({},[]);」 。這是實際的代碼嗎?放在這一行? – Elder

+0

是的,它不代表在代碼中,我編輯了原始文章以更好地解釋發生了什麼。在這種情況下,「callback.apply({},[])」的含義與「callback()」完全相同,您可以在這裏閱讀更多關於應用的信息:https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects /功能/應用 –

1

你可以使用負載方法的圖像,如:

$('someElement img').load(function(){ 
    //all loaded 
}); 

您的意思是類似的東西

+0

我已經嘗試過這一點,但似乎不能滿足我的要求。 TNX – Elder