javascript - js image's onload is not executed after the image is loaded
大家讲道理
大家讲道理 2017-05-19 10:12:08
0
4
585

1. The assumed effect is that every time a picture is loaded, alert "1", but the actual effect is that after all pictures are loaded, alert 4 times.
2. The following is the code, please help me clarify it.
//imgArray[] There are 4 picture links here. I won’t write them if they are too long.
var count = 0;

for (var i = 0; i < imgArray.length; i++) {
    var imgobj = new Image();
    imgobj.onload = function () {
        alert("1");
        if (count == imgArray.length - 1) {
            loading.style.display = "none";
        }
        ++count;

    };

    imgobj.src = imgArray[i];
}
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
phpcn_u1582
// 这是经典闭包问题了,最简单的方法,var改成let试试
for (let i = 0; i < imgArray.length; i++) {
    let imgobj = new Image();
    imgobj.onload = function () {
        alert("1");
        if (count == imgArray.length - 1) {
            loading.style.display = "none";
        }
        ++count;

    };

    imgobj.src = imgArray[i];
}
仅有的幸福

Write a loading method and it’s done recursively

巴扎黑

var count = 0;
for (var i = 0; i < imgArray.length; i++) {

(function(){
    var imgobj = new Image();
    imgobj.onload = function () {
        alert("1");
        if (count == imgArray.length - 1) {
            loading.style.display = "none";
        }
        ++count;
    };
    imgobj.src = imgArray[i];
})(i)

}

仅有的幸福

The problem has been solved. It should be that the picture was quoted incorrectly. Sorry for wasting everyone’s time!

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQIAJgAmAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKCh MoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoK... slightly....
The above is the referenced image address, change it to the following and it will execute normally,
https://ss1.bdstatic .com/70cF…

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template