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];
}
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];
}
巴扎黑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)
}
仅有的幸福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…