search

Home  >  Q&A  >  body text

javascript - js image's onload is not executed after the image is loaded

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];
}
大家讲道理大家讲道理2770 days ago576

reply all(4)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:14:08

    // 这是经典闭包问题了,最简单的方法,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];
    }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:14:08

    Write a loading method and it’s done recursively

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:14:08

    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)

    }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:14:08

    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…

    reply
    0
  • Cancelreply