Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 调用一组匹配项上的一个事件_Javascript_Jquery - Fatal编程技术网

Javascript 调用一组匹配项上的一个事件

Javascript 调用一组匹配项上的一个事件,javascript,jquery,Javascript,Jquery,我是这样做的: $('div > img').onAll('load', function() { alert('Loaded!') }) 只会提醒“已加载!”一次 我不想要这个: $('div > img').on('load', function() { alert('Loaded!'); }); 因为这将在加载每个图像后调用事件 jQuery中是否有调用一组匹配事件的就绪函数?或者我必须为它编写自定义函数吗?试试这个 var $images = $("div > im

我是这样做的:

$('div > img').onAll('load', function() { alert('Loaded!') })
只会提醒“已加载!”一次

我不想要这个:

$('div > img').on('load', function() { alert('Loaded!'); });
因为这将在加载每个图像后调用事件

jQuery中是否有调用一组匹配事件的就绪函数?或者我必须为它编写自定义函数吗?

试试这个

var $images = $("div > img")
    , imageCount = $images.length
    , counter = 0;

    // one instead of on, because it need only fire once per image
    $images.one("load",function(){

         // increment counter everytime an image finishes loading
         counter++;
         if (counter == imageCount) {

             // do stuff when all have loaded
             alert('Loaded!'); 
         } 
    }).each(function () {
        if (this.complete) {

            // manually trigger load event in
            // event of a cache pull
            $(this).trigger("load");
          }
    });

试试这样的

$('body').on('load','div > img',function() { alert('Loaded!') });
快乐编码:)

创建自己的方法

$.fn.onAll = function(ev, callback) {
    var xhr = [];
    this.each(function() {
        var def = new $.Deferred();
        var ele = document.createElement(this.tagName.toLowerCase());
        ele['on'+ev] = function() {
            def.resolve();
        }
        ele.src = this.src;
        xhr.push(def);
    });
    $.when.apply($, xhr).then(callback);
    return this;
}
用作

$('div > img').onAll('load', function() { alert('Loaded!'); });

您认为body是img的后代?:)@用户2394156:对不起,我忘了更换选择器是的,我希望有一种没有附加功能的方法,但谢谢。