的我做什麼像一個事件:「加載」,這將提醒調用一組比賽
$('div > img').onAll('load', function() { alert('Loaded!') })
只有一次
我不希望這樣的:
$('div > img').on('load', function() { alert('Loaded!'); });
,因爲每一個圖像已經加載
在此之後會調用事件是否有jQuery的任何現成函數,在調用事件一組比賽?或者我必須爲它編寫一個自定義函數?
的我做什麼像一個事件:「加載」,這將提醒調用一組比賽
$('div > img').onAll('load', function() { alert('Loaded!') })
只有一次
我不希望這樣的:
$('div > img').on('load', function() { alert('Loaded!'); });
,因爲每一個圖像已經加載
在此之後會調用事件是否有jQuery的任何現成函數,在調用事件一組比賽?或者我必須爲它編寫一個自定義函數?
創建您自己的方法
$.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!'); });
試試這個
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!') });
編碼快樂:)
在你看來身體是IMG的後裔? :) – user2394156
@ user2394156:對不起,我忘記互換選擇器 – dreamweiver
是的,我希望有一種方式沒有額外的功能,但謝謝。 – user2394156