0

我正在使用此代码预加载图像并稍后通过 id 引用它们。它可以在大多数浏览器和 ipad 上运行,但 IE8 会生成此错误:

'无法获取未定义空引用的属性'目标''

这是我的代码:

var images = [{id:"kids", url:"assets/driekids.png"}, {id:"title",url:"assets/gametitle.png"}];
var assets = [];
var fnCallback = fn;
var loaded = 0;

this.startLoading = function() {
    var t = this;
    for(var i = 0;i<images.length;i++){
        var r = new Image();
        r.src = images[i].url;
        r.name = images[i].id;
        r.onload = function(){t.checkLoaded();};
    }
}

this.checkLoaded = function(e) {    
    this.assets[e.target.name] = e.target;  
    loaded++;
    if(loaded == images.length) fnCallback();       
}

我的问题:这种图像预加载方式是否可以在 IE8 上使用 new Image() 进行?

4

1 回答 1

1

在 IE 中你会得到这样的事件对象:

window.event

所以你必须修改你的代码:

this.startLoading = function() {
    var t = this;
    for(var i = 0;i<images.length;i++){
        var r = new Image();
        r.src = images[i].url;
        r.name = images[i].id;
        r.onload = t.checkLoaded; // you dont want an anonymous function here
    }
}

this.checkLoaded = function(e) {
    // get the event object for both IE and other browsers
    var event = e || window.event;
    var target = e.target || event.srcElement ;
    this.assets[target.name] = target;  
    loaded++;
    if(loaded == images.length) fnCallback();       
}
于 2013-10-28T16:47:56.890 回答