问题描述
我在这里得到了代码像这样的数组var pics = ['1.jpg','2.jpg','3,jpg'];
i got the code herea array like this var pics = ['1.jpg','2.jpg','3,jpg'];
遍历数组
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一直都在加载,怎么解决呢?我在哪里错了?
but all i got is 3,jpg is loaded all the time,how to solve this? where am i wrong?
推荐答案
这是因为.load
事件是异步触发的. JavaScript在继续执行脚本之前不会等待所有图像加载,因此您需要在每次加载图像时执行测试.我也使您的代码更具可读性.
That's because the .load
event fires asynchronously. 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. 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");
}
});
}
侧面说明:使用for...in
遍历数组将产生讨厌的结果.特别是,它将包含Array
的所有属性,因此,简而言之,不要这样做 :) 亲自看看.
Side note: traversing an array using for...in
will yield nasty results. In particular, it will include all properties of Array
, so in short, don't do it :) See for yourself.
另一件事,当图像被缓存时,在某些浏览器中加载事件可能不会触发.为避免此问题,您可以在设置了complete
属性的每个图像上手动触发.load
事件.
Another thing, the load event may not fire in some browsers when the image has been cached. To avoid this problem, you can manually fire the .load
event on each image which has its complete
property set.
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");
});
}
这篇关于如何检查imgs数组是否已满载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!