我有以下内容:
var ImageArray = [];
var Images = $('#ImageSelection').children('img');
var i = 0;
Images.each(function() {
var ImageSource = $(this).attr('src');
var ImageTitle = $(this).attr('alt');
var ImageHeight;
getImageDimensions(ImageSource, function(data) {
ImageHeight = data.height;
alert(typeof ImageHeight + ' ' + ImageHeight);
});
alert(typeof ImageHeight + ' ' + ImageHeight);
$(this).attr('id', i);
ImageArray[i] = {
'src': ImageSource,
'title': ImageTitle,
'height': ImageHeight,
'id': i
};
i++;
});
运行此代码后,ImageArray[0].height
未定义,但回调函数中的警报显示高度很好,而不在回调中的警报显示未定义。
getImageDimensions:
function getImageDimensions(path, callback) {
var img = new Image();
img.onload = function() {
callback({
height: img.height
});
}
img.src = path;
}