简体   繁体   English

如何检查img数组是否已满载

[英]how to check a array of imgs is fully loaded

i got the code here a array like this var pics = ['1.jpg','2.jpg','3,jpg']; 我在这里得到的代码是这样的数组var pics = ['1.jpg','2.jpg','3,jpg'];

loop throught the array 遍历数组

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');}

but all i got is 3,jpg is loaded all the time, how to solve this? 但是我一直都是3,jpg加载,怎么解决呢? where am i wrong? 我哪里错了?

That's because the .load event fires asynchronously. 这是因为.load事件是异步触发的。 JavaScript will not wait for all the images to load before proceeding with the script execution, so you need to perform the test each time an image has loaded. JavaScript在继续执行脚本之前不会等待所有图像加载,因此您需要在每次加载图像时执行测试。 I've made your code a bit more readable too. 我也使您的代码更具可读性。

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");   
        }
    });
}

Side note: traversing an array using for...in will yield nasty results. 旁注:使用for...in遍历数组会产生讨厌的结果。 In particular, it will include all properties of Array , so in short, don't do it :) See for yourself. 特别是,它将包括Array所有属性,因此,简而言之, 不要这样做 :) 自己动手。

Another thing, the load event may not fire in some browsers when the image has been cached. 另一件事,当缓存了图像时,在某些浏览器中可能不会触发load事件。 To avoid this problem, you can manually fire the .load event on each image which has its complete property set. 为避免此问题,您可以在设置了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");
    });
}

You need to scope the i variable to retain the current value in the loop. 您需要确定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');
        }
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM