我有一个位于here的小提琴,说明了我的问题,即当我使用Image
对象加载图像时,会调用onload
,但返回的对象仍为undefined
这是代码,以防小提琴消失在虚空中:
var ImageManager = function() {
var _images = [],
_loaded = 0;
var precache = function(imageArray) {
if (!(imageArray instanceof Array)) {
return;
}
for (var i = 0; i < imageArray.length; i++) {
if (typeof imageArray[i] !== 'string') {
continue;
}
_images[i] = new Image();
_images[i].onload = function() {
_loaded++;
document.write('<p>Successfully loaded: ' + imageArray[i] + ' [' + _loaded + '/' + imageArray.length + ']</p>');
}
_images[i].onerror = function() {
document.write('<p>Unable to load: ' + imageArray[i] + '</p>');
}
_images[i].src = imageArray[i];
}
};
var get = function(imagePath) {
if (!_images.hasOwnProperty(imagePath)) {
document.writeln('<p>' + imagePath + ' isn\'t precached!</p>');
return null;
}
return _images[imagePath];
};
return { get: get, precache: precache }
};
// Test case starts here:
var testImages = [
'http://jsfiddle.net/img/logo.png',
'http://jsfiddle.net/img/logo.png',
'http://jsfiddle.net/img/logo.png'
];
var imageManager = new ImageManager();
imageManager.precache(testImages);
示例输出:
成功加载:未定义[1/3]
成功加载:undefined [2/3]
成功加载:undefined [3/3]
按照惯例,我可能会忽略一些显而易见的事情。你们,无所不知的神谕,帮助我。
答案 0 :(得分:1)
i
始终等于imageArray.length - 1
,因为i
在循环期间会增加。将环的主体包裹在一个封闭中:
此外,即使出于调试目的,也不要使用document.write
。使用console.log(..)
,alert(..)
或至少document.body.innerHTML += ..
。
for (var i = 0; i < imageArray.length; i++) {
if (typeof imageArray[i] !== 'string') {
continue;
}
(function(i){ //<-- This
_images[i] = new Image();
_images[i].onload = function() {
_loaded++;
console.log('Successfully loaded: ' + imageArray[i] + ' [' + _loaded + '/' + imageArray.length + ']');
}
_images[i].onerror = function() {
console.log('Unable to load: ' + imageArray[i]);
}
_images[i].src = imageArray[i];
})(i); //<-- This
}