测试是否已加载所有图像 [英] Test if all images are loaded

查看:160
本文介绍了测试是否已加载所有图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试是否所有图像都已加载:

Here is my attempt at the ability to test if all images are loaded:

for (var i = 0; i < imgCount; i ++) {
    loadArr[i] = false
    imgArr[i] = new Image()
    imgArr[i].src='img'+i+'.png'
    imgArr[i].onload = function() {
        loadArr[i] = true //but wait! At the end of
                          //the loop, i is imgCount
                          //so this doesn't work.
    }
}

问题是循环完成后,变量 i imgCount 。这意味着所有其他已加载标志在加载图像时永远不会设置为 true

The problem is that once the loop is done, the variable i is imgCount. That means all the other "loaded" flags never get set to true when their images are loaded.

是否存在某种方法可以为图像添加已加载属性,或者是否有解决此问题的方法?

Is there some way to add a "loaded" property to an image, or is there some workaround to this problem?

推荐答案

您需要使用闭包来定义onload函数:

You need to define the onload function using a closure:

for (var i = 0; i < imgCount; i ++) {
    loadArr[i] = false
    imgArr[i] = new Image()
    imgArr[i].src='img'+i+'.png'
    imgArr[i].onload = (function(i){
        return function(){ loadArr[i] = true }
    })(i);
}

这是 jsFiddle ,它演示了这种情况在类似的情况下工作。

Here's a jsFiddle which demonstrates this working in a similar scenario.

另外,请注意您当前选择的解决方案答案实际上不起作用:

Also, note that the solution you've currently selected as the answer doesn't actually work:

imgArr[i].onload = (function() {
        loadArr[i] = true;
    })();

立即评估此功能。这意味着在循环中,loadArr的每个元素都设置为true,就像onload事件一样。该代码在功能上与以下内容完全相同:

This function is evaluated immediately. This means that in the loop, each element of the loadArr is set to true as is the onload event. That code is functionally identical to:

imgArr[i].onload = loadArr[i] = true;

这篇关于测试是否已加载所有图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆