jQuery:如何检查数组中的所有图像何时加载?

发布于 2024-12-05 00:42:59 字数 338 浏览 2 评论 0原文

我有一个图像数组(图像的确切数量各不相同),当它们全部加载时,我想要执行一些代码。

我尝试过,但它不起作用:

myImgArray.load(function(){
    alert('loaded');
});

我明白了

33:未捕获类型错误:对象 [object Object]、[object Object]、[object Object]、[object Object] 没有方法“load”

我不认为for循环或类似的东西会起作用,因为图像可能,并且可能会以“随机”顺序加载。

I have an array of images (the exact number of images varies), and when they all load I want some code to execute.

I tried this but it doesn't work:

myImgArray.load(function(){
    alert('loaded');
});

I get

33: Uncaught TypeError: Object [object Object],[object Object],[object Object],[object Object] has no method 'load'

I don't think a for loop or something similar would work because the images might, and probably will, load in 'random' order.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小梨窩很甜 2024-12-12 00:42:59

我知道的唯一方法是为每个图像附加一个加载处理程序,并记录已加载的图像数量。当您达到总数时,它们就全部加载完毕。

下面是执行此操作的代码:

var urls = [
    "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg",
    "http://photos.smugmug.com/photos/344292111_SvSfK-Ti.jpg",
    "http://photos.smugmug.com/photos/344291168_nErcq-Ti.jpg"
];

var imgs = [];
var cnt = 0;

for (var i = 0; i < urls.length; i++) {
    var img = new Image();
    img.onload = function() {
        ++cnt;
        if (cnt >= urls.length) {
            // all images loaded here
        } else {
            // still more images to load
        }
    };
    img.src = urls[i];
    imgs.push(img);
}

您可以在此处查看它的实际操作:http://jsfiddle.net/jfriend00/7KF7V/

对于要实现此功能,必须在设置 .src 属性之前分配 onload 处理函数,因为如果图像位于浏览器缓存中,onload 可能会在之前立即触发.onload 已分配,因此错过了该事件。

The only way I know of to do it is to attach a load handler for each image and keep a count of how many have been loaded. When you reach your total, then they've all been loaded.

Here's code that does that:

var urls = [
    "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg",
    "http://photos.smugmug.com/photos/344292111_SvSfK-Ti.jpg",
    "http://photos.smugmug.com/photos/344291168_nErcq-Ti.jpg"
];

var imgs = [];
var cnt = 0;

for (var i = 0; i < urls.length; i++) {
    var img = new Image();
    img.onload = function() {
        ++cnt;
        if (cnt >= urls.length) {
            // all images loaded here
        } else {
            // still more images to load
        }
    };
    img.src = urls[i];
    imgs.push(img);
}

You can see it in action here: http://jsfiddle.net/jfriend00/7KF7V/

For this to work, the onload handler function has to be assigned before the .src property is set because if the image is in the browser cache, onload may fire immediately before .onload is assigned, thus missing the event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文