2011-08-19 61 views
1

我在这里得到的代码 这样的数组var pix = ['1.jpg','2.jpg','3,jpg'];如何检查一个imgs数组是完全加载的

循环throught阵列

var j = 0; 
var(var i in pics){ 
$(document.createElement(img)).attr('src',pics[i]).load(function(){ 
    alert(pics[i]+'is loaded'); 
    j++; 
})} 

if(j == pics.length){ 
alert('fully loaded');} 

但我得到的是3,JPG加载所有的时间, 如何解决这个问题?我在哪里错了?

+0

大傻瓜: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 –

回答

1

这是因为.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"); 
    }); 
} 
+0

感谢您的评论,但我在控制台中运行您的代码,但我每次都得到最后一张图片警报,( 3.jpg被加载),也许你可以试试你的代码 – vikingmute

+0

@vikingmute - 你试过第二个例子吗? – karim79

0

您需要将i变量的范围保留在循环中的当前值。

var j = 0; 

for(var i = 0; i < pics.length; i++){ 
    addHandler(i); 
} 

function addHandler(this_i) { 

    $(document.createElement('img')).attr('src',pics[i]).load(function(){ 
     alert(pics[this_i]+'is loaded'); 
     j++; 

     if(j == pics.length){ 
      alert('fully loaded'); 
     } 
    }); 

} 
相关问题