我的 for
语句中有一个 onload
函数,它会产生意外的结果。
for
循环循环遍历图像数组。我希望此循环对数组中的每个图像执行 onload
,并且只有在完成后才继续执行 for
循环中的下一次迭代。 onload
在执行之前等待图像元素加载。
for (index = 0; index < lightboxImages.length; index++) {
console.log('index :' + index);
// when the current image has finished loading
lightboxImages[index].onload = function() {
console.log('image ' + index + ' loaded.');
};
}
数组中只有三个元素,通过我的 console.log
语句,我期望控制台中出现类似以下内容:
index : 0
image 0 loaded.
index : 1
image 1 loaded.
index : 2
image 2 loaded.
但是我得到的输出是这样的:
index : 0
index : 1
index : 2
image 3 loaded.
image 3 loaded.
image 3 loaded.
如何在 onload
完成之前防止迭代?
我也尝试过这样的事情:
// just an index variable as an example
var counter = 2;
toImage(i) {
if (i == counter) {
console.log('hooray');
}
else {
toImage(i++);
}
}
toImage(0);
这导致了导致页面崩溃的调用堆栈问题 - 我没有将其包含在原始帖子中,因为我认为这是一个完全独立的问题,但也许我应该回顾一下。我想我在这里的递归尝试是错误的。
最佳答案
另一种选择是递归调用:
function loop(lightboxImages, index) {
if (index === lightboxImages.length) return;
lightboxImages[index].onload = function() {
console.log('image ' + index + ' loaded.');
loop(lightboxImages, ++index);
};
}
loop(lightboxImages, 0);
关于javascript - 如何等待onload语句完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394873/