祝大家健康快乐!一个写好的脚本,应该遍历所有的图片,如果图片加载不出来,那么脚本应该把父 block 隐藏在.Parent_block类下,也就是我有3个 block ,有一个图片在中央 block 中,但不在其他两个 block 中,这意味着它们应该具有属性 display:none
但是我做错了什么。我哪里弄错了?
let parent_block = document.querySelectorAll('.Parent_block');
let image_b = document.querySelectorAll('.Child_Img');
image_b.forEach(function(){
if(image_b.onerror){
for(let parent_block of hide){
hide.style.display = 'none';
}
}
})
.Parent_block{
width:30%;
margin:0;
padding:0;
margin-left:10px;
margin-top:10px;
border:1px solid black;
display:inline-block;
height:250px;
}
img{
height:inherit;
width:100%;
<figure class="Parent_block"> <!-- ***** this block should disappear ***** =( -->
<img class="Child_Img" src="">
<figcaption class ="Img_text">1</figcaption>
</figure>
<figure class="Parent_block">
<img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg">
<figcaption class ="Img_text">2</figcaption>
</figure>
<figure class="Parent_block"> <!-- ***** and this one too ***** =( -->
<img class="Child_Img" src="">
<figcaption class ="Img_text">3</figcaption>
</figure>
最佳答案
脚本有一些问题。
image_b.forEach
并在其中尝试访问 image_b.onerror
。这将不起作用,因为 image_b
是一个数组。onerror
是事件而不是属性。所以不能这样访问。for(let parent_block of hide)
是错误的。固定代码
逻辑
Child_Img
的所有元素。onerror
事件,类名 Child_Img
。Parent_block
的元素并将其隐藏。工作 fiddle
let image_b = document.querySelectorAll('.Child_Img');
image_b.forEach(function (img) {
img.onerror = function(image) {
img.closest(".Parent_block").style.display = 'none';
}
})
.Parent_block {
width: 30%;
margin: 0;
padding: 0;
margin-left: 10px;
margin-top: 10px;
border: 1px solid black;
display: inline-block;
height: 250px;
}
img {
height: inherit;
width: 100%;
}
<figure class="Parent_block">
<!-- ***** this block should disappear ***** =( -->
<img class="Child_Img" src="">
<figcaption class="Img_text">1</figcaption>
</figure>
<figure class="Parent_block">
<img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg">
<figcaption class="Img_text">2</figcaption>
</figure>
<figure class="Parent_block">
<!-- ***** and this one too ***** =( -->
<img class="Child_Img" src="">
<figcaption class="Img_text">3</figcaption>
</figure>
https://stackoverflow.com/questions/71670961/