这是因为.load
事件触发异步。在继续执行脚本之前,JavaScript不会等待所有图像加载,因此每次加载图像时都需要执行测试。我也让你的代码更具可读性。
var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
$(document.createElement(img)).attr('src', pics[i]).load(function() {
alert(pics[i] + 'is loaded');
loadCounter++;
if(loadCounter === len) {
alert("all are loaded");
}
});
}
边注:遍历使用for...in
将产生讨厌的结果的数组。特别是,将包括Array
所有属性,因此,在短期,不这样做 :) See for yourself.
另一件事,当图像已被缓存负载事件可能不会触发在某些浏览器。为避免此问题,您可以手动触发其complete
属性设置的每个图像上的.load
事件。
var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
$(document.createElement(img)).attr('src', pics[i]).one("load", function() {
alert(pics[i] + 'is loaded');
loadCounter++;
if(loadCounter === len) {
alert("all are loaded");
}
}).each(function() {
if(this.complete) $(this).trigger("load");
});
}
大傻瓜:http://stackoverflow.com/questions/4857896/jquery-callback-after-all-images-in-dom-are-loaded http://stackoverflow.com/questions/5424055/check-if-images-is-loaded http://stackoverflow.com/questions/6488104/how-to-know-when-all-images-inside-a-specific-div-are-loaded http:///stackoverflow.com/questions/5410580/jquery-function-execute-when-all-images-are-loaded –