!DOCTYPE htmlhtml lang=enhead meta charset=UTF-8 title据说我是反派大小姐-预告title link rel=stylesheet type=textcss href=manhuacssheadbodyscriptfunction yeShua b var i = 0; 标志变量 imgonerror = function
要在图片加载失败时停止while循环,可以在img的onerror事件中设置一个标志变量,当图片加载失败时,将标志变量设为-1,然后在while循环中通过判断标志变量的值来确定是否继续循环。
以下是修改后的代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>据说我是反派大小姐-预告</title>
<link rel="stylesheet" type="text/css" href="manhua.css">
</head>
<body>
<script>
function yeShu(a, b) {
var i = 0;// 标志变量
var img = new Image();
img.onerror = function() {
alert(i);
i = -1;
};
while(i >= 0){
var div = document.createElement('div');
div.className = "box";
document.body.appendChild(div);
img.src = "https://jsmov2.a.yximgs.com/ufile/atlas/NTIyMTY0MjM3NzE0OTMwMzcyNF8xNjYwMjc3NDUyMTc3_" + i + ".jpg";
if (document.getElementsByClassName('box').length > 0) {
document.getElementsByClassName('box')[i].appendChild(img);
}
i++;
if(i > 10){
i = -1;
}
}
}
yeShu("1","1");
</script>
</body>
</html>
在上述代码中,我将img的创建放在了函数内部,并在while循环中使用同一个img元素来加载不同的图片。这样,在每次循环时,img的onerror事件会重新绑定,以便在图片加载失败时触发。同时,我还将图片加载失败时的alert(i)语句放在了onerror事件中,以便在测试时查看加载失败的图片序号
原文地址: https://www.cveoy.top/t/topic/iyj9 著作权归作者所有。请勿转载和采集!