[英]Binding onload event on image object in jQuery
我的網站上有以下代碼:
backgroundImages[bg_img_path_b]=new Image();
backgroundImages[bg_img_path_b].src = bg_img_path_b;
backgroundImages[bg_img_path_b].loaded="loading";
//jQuery(backgroundImages[lastImage]).unbind('load.backgroundImages');
jQuery(backgroundImages[bg_img_path_b]).bind('load.backgroundImages',function(){
if(typeof callback=='function'){
callback.call(this, bg_img_path_b);
if(showLoading) hideLoadingDC();
}
}).bind('load.cache', function(){
backgroundImages[bg_img_path_b].loaded="true";
});;
有用作頁面包裝器背景圖像的大型圖像庫。 由於速度原因,我需要預加載圖像(圖像非常大)。 所以我有這段代碼(實際上只是更大的 function 的一部分,它包裝了緩存等,但是當圖像不在緩存中時會觸發這幾行)。
backgroundImages
是Image對象的大數組,key是path是圖片的路徑。 每個圖像 object 都有我的屬性“加載”,它表示圖像是否已經加載,或者當前正在加載 state。
正如您從我的代碼中看到的那樣,我在加載圖像時調用回調 function(背景發生變化等)
但是我有一個 IE <9 的問題,回調沒有成功啟動(但不是每次)..當我第一次加載我的頁面時它加載正確,但是每當我再次調用這個 function 時,它會正確地通過而沒有錯誤, 但加載事件沒有觸發..
我真的不知道哪里可能出錯,在除舊版 IE 之外的所有瀏覽器中它工作正常..
實際上我需要調試事件是否正確綁定,但我無法在調試器的加載項下在 IE 和 Chrome 中看到它:(
請幫助我完全搞砸了,真的不知道該怎么辦。
所以幾天前我終於找到了解決我的問題的方法..如果我首先綁定onload事件然后設置Image的url,或者首先設置url然后綁定事件似乎很重要..示例
var photo = new Image();
photo.url = "http://www.something.com/something.jpg";
$(photo).bind('load',doSomething());
var photo = new Image();
$(photo).bind('load',doSomething());
photo.url = "http://www.something.com/something.jpg";
第一個變體通常運行正常,但有時會失敗(在較舊的 IE 中)..但是第二個變體肯定可以正常工作..
您使用的是哪個 jQuery API 版本? 嘗試使用最新版本的 jQuery。
否則,使用這個簡單的 JavaScript 代碼在主體加載時調用 function 來加載圖像:
var myimages = new Array();
var path = "images/gallery/";
function preloadimages() {
for (i = 0; i < preloadimages.arguments.length; i++) {
myimages[i]=new Image();
myimages[i].src=path+preloadimages.arguments[i];
}
}
// Enter name of images to be preloaded inside parenthesis with douable quotes.
// Extend list as desired with comma.
preloadimages("gImg1.jpg","gImg2.jpg","gImg3.jpg","gImg4.jpg" /*, etc...*/);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.