不确定我是否误用了 new Image(),我使用下面的代码遇到了 json 对象的奇怪对象顺序。
$.ajax({
type: 'GET',
url: '/' + getUsername() + '/photos',
success: function(data) {
if (data.length > 0) {
$.each(data, function() {
var caption = this.caption
var albumPhoto = '';
albumPhoto = 'http://example.com/' + this.photo;
var temp_img = new Image(),
albumPhotoWidth, albumPhotoHeight
temp_img.src = albumPhoto;
temp_img.onload = function() {
var photosObj = {
src: albumPhoto,
title: caption,
w: this.naturalWidth,
h: this.naturalHeight
};
pswpAlbum_Items.push(photosObj);
}
});
}
}
});
}
pswpAlbum_Items 结果不一致,我的照片顺序不一致,当我尝试在私有(private)模式下浏览器永远不会获取缓存图像时,我发现了这个错误。知道为什么吗?
最佳答案
您的图像可能在不同时间加载。您应该考虑将它们添加到 onload
事件的数组 outside 中,或者使用对象作为映射,并使用回调中的 index
参数每个
。
关于javascript - 在 javascript 中使用 $.each 和 new Image() 时顺序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40466325/