在javascript中使用$ .each和new Image()时的顺序不一致

时间:2016-11-07 13:25:19

标签: javascript jquery

我不确定是否错过了新的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结果不一致,我的照片的顺序不一致,当我在私人模式下尝试浏览器永远不会获得缓存图像时,我发现了这个错误。有什么线索的原因?

2 个答案:

答案 0 :(得分:0)

您的图片可能会在不同时间加载。您应该考虑将它们添加到onload事件的数组中,或者将对象用作地图,并使用index回调中的each参数。

答案 1 :(得分:0)

我相信您正在尝试将图片加载到尺寸未知的照片中吗?

你可以试试这个

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