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

Inconsistent order when using $.each and new Image() in javascript

本文关键字:new Image each 中的 顺序 不一致 javascript 使用      更新时间:2023-09-26

不确定我是否滥用了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