jQuery中图像对象上的绑定onload事件

Binding onload event on image object in jQuery

本文关键字:绑定 onload 事件 图像 对象 jQuery      更新时间:2023-09-26

我的网站上有以下代码:

 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";
                        });;

有一个大型的图片库用作页面包装的背景图片。由于速度的原因,我需要预加载图像(图像相当大)。所以我有了这段代码(实际上只是更大函数的一部分,它封装了缓存等等,但这几行是在图像不在缓存中时激发的)。

backgroundImages是图像对象的大数组,关键是路径是图像的路径。每个图像对象都有我的属性"已加载",它表示图像是否已经加载,或者当前处于加载状态。

正如你从我的代码中看到的,当图像加载时,我正在调用回调函数(背景等发生了变化)

但我对I.E<9,回调没有成功启动(但不是每次都启动)。。当我第一次加载页面时,它会正确加载,但每当我再次调用此函数时,它都会正确运行,不会出错,但加载事件不会触发。。

我真的不知道哪里会有错误,在所有浏览器中,除了旧的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代码在body onload上调用函数时加载图像:

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...*/);