gpt4 book ai didi

Javascript:图像错误处理和嵌套

转载 作者:行者123 更新时间:2023-12-03 02:10:55 24 4
gpt4 key购买 nike

我想要一个错误处理脚本。如果找不到图像,请删除(或隐藏)加载失败的标签。我将不胜感激任何帮助!

HTML DOM:

<div class="swiper-slide" data-index="2" style="width: 145px; margin-right: 10px;">
<div class="swiper-slide-inside ">
<div class="align-vertical">
<img src="images/product_images/gallery_images/0690-05-bx_3.jpg" alt="Mobile" data-magnifier-src="images/product_images/popup_images/0690-05-bx_3.jpg">
</div>
</div>
</div>

JS:

document.querySelectorAll(".swiper-slide .img-responsive")[0].addEventListener("error", myFunction);

function myFunction() {
console.log('Image not found.');
document.querySelectorAll('.swiper-slide')[0].style.visbility = "hidden";
}

最佳答案

有几个问题

  • img 标记没有您在选择器中使用的类
  • 您尝试先隐藏 swiper-slide,而不是父级 swiper-slide

演示

document.querySelectorAll(".swiper-slide img")[0].addEventListener("error", myFunction);

function myFunction(event) {
console.log('Image not found.');
//use document.querySelector('.swiper-slide').style.display = "none" if there is only one such element and discard below line
event.target.parentNode.parentNode.parentNode.style.display = "none";
}
<div class="swiper-slide" data-index="2" style="width: 145px; margin-right: 10px;">
<div class="swiper-slide-inside ">
<div class="align-vertical">
<img src="images/product_images/gallery_images/0690-05-bx_3.jpg" alt="Mobile" data-magnifier-src="images/product_images/popup_images/0690-05-bx_3.jpg">
</div>
</div>
</div>

关于Javascript:图像错误处理和嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com