jQuery .one()加载和错误事件不起作用 [英] jquery .one() load and error events not working

查看:136
本文介绍了jQuery .one()加载和错误事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的html,我希望一个事件在加载最后一个图像后,或者在加载最后一个图像时出现错误时触发.这是我的代码

i have a simple html, that i want an event to trigger once the last image is loaded, or if there is an error on the last image being loaded. here is my code

html

<div id="compare-table-scrollable">
    <img src="www.bla.com/1.png" />
    <img src="www.bla.com/2.png" />
    <img src="www.bla.com/3.png" />
</div>

jQuery

var imageCount = $('#compare-table-scrollable img').length;
var counterIMG = 0;
$('#compare-table-scrollable img').one("load error",function(){
           counterIMG++;
           if (counterIMG == imageCount)  // do stuff when all have loaded
           {
                alert(counterIMG);
           }
});

这是我的 FIDDLE

推荐答案

这是我前一段时间写给自己的一个.它与上面的内容非常相似,但功能更强大...

Here's one I wrote myself a while back. It's very similar to what you have above, but a little more robust...

function onImagesLoaded($container, callback) {
    var $images = $container.find("img");
    var imgCount = $images.length;
    if (!imgCount) {
        callback();
    } else {
        $("img", $container).each(function () {
            $(this).one("load error", function () {
                imgCount--;
                if (imgCount == 0) {
                    callback();
                }
            });
            if (this.complete) $(this).load();
        });
    }
}

以及如何使用它...

And how to use it...

onImagesLoaded($("#compare-table-scrollable"), function() {
    alert("images loaded");
});

请注意,添加了if (this.complete),该功能允许函数在调用函数之前对已缓存并因此加载的图像进行计数.

Notice the addition of if (this.complete), which allows the function to count images that are cached and therefore load before the function is called.

这篇关于jQuery .one()加载和错误事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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