有没有办法确定何时使用JS加载了4张图像? [英] Is there a way to determine when 4 images have been loaded using JS?

查看:75
本文介绍了有没有办法确定何时使用JS加载了4张图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有4张图片。我想在加载所有4个图像后触发JS事件。我当然不能确定将加载图像的顺序,因此我无法在最后一张图像上触发事件。一个想法是有一个计数器,但我想不出最好的方法来检查该计数器何时等于4,因为我不喜欢每200ms检查一次setTimeout()的想法。

I have 4 images on a page. I want to trigger a JS event once all 4 images are loaded. I of course can't be sure which order the images will be loaded in, so I can't trigger the event on the last image. One thought was to have a counter, but I can't think of the best way to check when that counter is equal to 4 as I don't like the idea of a setTimeout() checking every 200ms.

还有其他想法吗?

我在网站上使用jQuery,所以我觉得这可能会有所帮助。

I'm using jQuery on the site, so I'm thinking that might be some help.

这是图片HTML代码:

This is the image HTML code:

<img src="/images/hp_image-1.jpg" width="553" height="180" id="featureImg1" />
<img src="/images/hp_image-2.jpg" width="553" height="180" id="featureImg2" />
<img src="/images/hp_image-3.jpg" width="553" height="180" id="featureImg3" />
<img src="/images/hp_image-4.jpg" width="553" height="180" id="featureImg4" />


推荐答案

关于萨尔蒂的例子,最好使用闭包来避免全局变量,例如:

As regards Salty's example, it's best to use a closure to avoid global variables, like such:

$("img").load(function() {    
    var count = 0, numImages = $("img").size();

    return function () {
        if (++count === numImages) { 
            //All images have loaded    
        }
    };
}());

根据 jeroen的评论,我将硬编码的值替换为4( count == = 4 )使用jQuery size 函数,以便在函数内提供更大的灵活性。

As per jeroen's comment, I replaced the hardcoded value of 4 (count === 4) with the jQuery size function as to allow for more flexibility within the function.

这篇关于有没有办法确定何时使用JS加载了4张图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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