Test if all images are loaded

前端 未结 3 897
难免孤独
难免孤独 2021-01-19 00:35

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         


        
3条回答
  •  被撕碎了的回忆
    2021-01-19 01:13

    You must pass the index value to anonymous function like this,

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

提交回复
热议问题