使用$时顺序不一致.javascript中的each和new Image()
Inconsistent order when using $.each and new Image() in javascript
不确定我是否滥用了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结果不一致,我的照片的顺序不一致,当我在浏览器从未缓存图像的私有模式下尝试时,我发现了这个错误。知道为什么吗?
您的图像可能在不同时间加载。您应该考虑将它们添加到onload
事件之外的数组中,或者使用对象作为映射并使用each
回调中的index
参数。
我相信你正在尝试加载图像到未知尺寸的photoswipe对吗?
你可以试试这个
var items = [
{ src: 'http://........', w:0, h:0 },
{ src: 'http://........', w:0, h:0 }
];
var gallery = new PhotoSwipe( ..... );
gallery.listen('gettingData', function(index, item) {
if (item.w < 1 || item.h < 1) { // unknown size
var img = new Image();
img.onload = function() { // will get size after load
item.w = this.width; // set image width
item.h = this.height; // set image height
gallery.invalidateCurrItems(); // reinit Items
gallery.updateSize(true); // reinit Items
}
img.src = item.src; // let's download image
}
});
gallery.init();
来源:https://github.com/dimsemenov/PhotoSwipe/issues/796
相关文章:
- Image赢得't隐藏在滚动jQuery上
- 使用:new Image()控制加载html.src=html_URL
- 无法使用nodeJS在html中设置Image src
- image.onload事件和浏览器缓存
- SVG xml to image
- 如何在不使用 new 关键字的情况下从函数创建对象
- 为什么要做新的.Date()与new相差1小时.日期().到ISOString()
- “createImageData()”和“new ImageData(()”有何不同
- jQuery中的new Image()做什么
- 解释 var img = new Image();的工作
- New image().src将变量传递给PHP
- 在画布元素内的javascript中为new Image()设置边框颜色
- Javascript中的new Image()出现问题
- 使用$时顺序不一致.javascript中的each和new Image()
- 使用new Image()时javascript内存泄漏
- new Image()'将浏览器实现转化为node-webgl javascript实现
- Javascript new Image()没有加载图像
- 使用var i=new Image();i.src . .而不是真正的ajax信号仅远程命令
- “;(new Image()).src“;在onclick事件中
- “new Image()”和“document.createElement('img')”之间有区别吗