我正在使用此代码预加载图片并稍后通过id引用它们。 它适用于大多数浏览器和ipad,但IE8会产生此错误:
'无法获取未定义的空引用'
的属性'target'这是我的代码:
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上使用新的Image()?
答案 0 :(得分: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();
}