在图像对象jquery上绑定onload事件

时间:2011-06-16 10:06:22

标签: javascript jquery javascript-events onload

您好我的网站上有以下代码

 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是大对象的Image对象,关键是路径是图像的路径。每个Image obejct都有我的属性“已加载”,表示图像是否已加载,或者当前处于加载状态。

从我的代码中可以看出,我在加载图像时调用了回调函数(背景有变化等)。

但是我遇到了问题I.E< 9 ..回调未成功启动(但不是每次都启动)..当我首先加载我的页面时它正确加载,但是无论何时我再次调用此函数,它没有错误地正确通过,但是不会触发load事件..

我真的不知道哪里可能是一个错误,在所有浏览器中,除了较旧的IE,它工作正常..

实际上我需要调试事件是否正确绑定,但在调试器中的加载项下我无法在IE和Chrome中看到它:(

请帮助我完全搞砸了,真的不知道该怎么做..

2 个答案:

答案 0 :(得分:4)

前几天我终于找到了解决问题的方法..如果我首先绑定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中)..但第二个变种肯定是正常工作..

答案 1 :(得分:0)

您使用的是哪个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...*/);