【发布时间】:2019-02-09 04:56:26
【问题描述】:
- 我想按顺序添加新的 Image()。
例如,
当我不使用Onload 时,图像会按顺序附加。
但是当我使用Onload 时,图像并没有按顺序附加。
以下是 concole 日志,您可以在其中看到图像附加不按顺序。
/C:/Users/TSUBYAM/Desktop/Web/images/netherlands/netherlands_008.jpg:1 获取文件:///C:/Users/TSUBYAM/Desktop/Web/images/netherlands/netherlands_008.jpg net::ERR_FILE_NOT_FOUND 图片(异步)(匿名)@load_picture.js:19 load_picture.js:17 未找到:../images/netherlands/netherlands_008.jpg load_picture.js:13 找到:../images/netherlands/netherlands_006.jpg load_picture.js:13 找到:../images/netherlands/netherlands_001.jpg load_picture.js:13 找到:../images/netherlands/netherlands_003.jpg load_picture.js:13 找到:../images/netherlands/netherlands_005.jpg load_picture.js:13 找到:../images/netherlands/netherlands_004.jpg load_picture.js:13 找到:../images/netherlands/netherlands_002.jpg load_picture.js:13 找到:../images/netherlands/netherlands_007.jpg- 我也想在找到不存在的图片路径时退出循环。
我无法退出循环,因此我使用了“style.display = none”。所以我不显示不存在的图像。
这是我的代码。
let file_name = window.location.href.split('/').pop();
let country = file_name.split(/\./)[0];
let parent_img = document.getElementsByClassName("pic")[0];
for ( var i = 0; i < 8; i++)
{
// get file image
let pic_num = ("000" + (i + 1)).slice(-3);
let pic_name = `${country}_${pic_num}.jpg`;
let pic_path = "../images/" + country + "/" + pic_name;
let newImage = new Image();
newImage.onload = function(){
console.log(`Found: ${pic_path}`);
}
newImage.onerror = function(){
this.style.display = 'none';
console.log(`Not Found: ${pic_path}`);
}
newImage.src = pic_path;
newImage.alt = pic_name;
parent_img.appendChild(newImage);
}
【问题讨论】:
标签: javascript onload