所有图像加载后运行一个功能 [英] Run a function when all images are loaded

查看:72
本文介绍了所有图像加载后运行一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(var i = 0; i< images_list.length; i ++){
var img = new Image();
img.onload = function(){
images_objects.push(this);
showImages(images_objects);
};
img.onerror = function(){

};
img.src = images_links [i] .image_url;
}

我需要正常工作的是 showImages 函数。它的目的是当 images_object 被数组中的图像填充时,用jQuery显示所有加载的图像。现在它被错误地放置,只是为了让你知道我是如何尝试去做的。我想应该在加载图像后运行回调。如何做到这一点更好?

解决方案

只需使用辅助函数来存储新加载的图像,并检查是否所有图像

  ... 
img.onload = function(){
storeLoadedImage(本);
};
...

var storeLoadedImage = function(image){
images_objects.push(image);

if(images_objects.length === images_list.length){
showImages(images_objects);
}
};


I use a function like this to load images from an array:

for (var i = 0; i < images_list.length; i++) {
            var img = new Image();
            img.onload = function() {
                images_objects.push(this);
                showImages(images_objects);
            };
            img.onerror = function() {

            };
            img.src = images_links[i].image_url;
        }

What I need to make work properly is showImages function. Its purpose is to show all loaded images with jQuery when the images_object is filled with images from the array. Now it's placed incorrectly, just to give you an idea how I try to do it. I suppose there is something like a callback should be run after the images are loaded. How to do this better?

解决方案

Just use a helper function to store the newly loaded image and to check to see if all images have been loaded, might work.

...
img.onload = function() {
    storeLoadedImage(this);
};
...

var storeLoadedImage = function(image) {
    images_objects.push(image);

    if (images_objects.length === images_list.length) {
        showImages(images_objects);
    }
};

这篇关于所有图像加载后运行一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆