逐步加载和添加图像

3

我有一个问题一直解决不了。我做了一个简单的jQuery相册画廊,我有这个函数:

function loadAlbum (index) {
    for (var j=1; j < xmlData[index].length; j++) {

        var img = new Image();

        $(img).load(function() {
                    $(this).hide();
                    $('#album'+index+' .photoContainer').append(this);
                    $(this).fadeIn();
                })
                .error(function(){
                    //alert("Could not load one or more photo!");
                })
                .attr({
                    'src': xmlData[index][j],
                    'id': 'img'+index+j,
                    'class': 'photoFrame',
                    'width': newW,
                    'height': newH
                })
                .css({
                    'width': newW,
                    'height': newH
                });
    };
};

现在,您可以看到所有图像的src都是从包含数据的外部XML文件导入的(图像名称是连续的,例如:photo001.jpg,photo002.jpg等)。它们通过for循环在DOM中创建并附加到一个div中。你可能会问什么问题?我需要所有的图像按照XML数据指定的方式进行逐步附加,但只有在本地计算机上才会发生这种情况,如果上传到某个服务器上,则不会发生。我想这是由于每个图像的加载时间取决于其大小而不同...但我仍然无法解决这个问题。有人有任何想法吗?
1个回答

6
以下尝试逐个加载图片。一旦加载了一张图片,接下来的图片将在此之后加载。
function loadAlbum(index) {
    var i = 0;
    var j = xmlData[index].length;
    function loadImage() {
         if (i >= j) return;

         // do what you're doing in the loop except for ....
         $(img).load(function() {
             $(this).hide();      
             $('#album'+index+' .photoContainer').append(this);
             $(this).fadeIn();
             // increments i by 1 and calls loadImage for the next image.
             i++;
             loadImage();
         // etc.
    }
    loadImage();
}

我将把它留给你作为练习来确定如何同时加载多个图像并仍然保持排序 :)

哇塞,非常感谢!一切都运行得非常顺畅和完美...现在我感觉自己像个真正的新手 XD! - RDX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接