javascript - 如果其中没有图像, block 就会消失

祝大家健康快乐!一个写好的脚本,应该遍历所有的图片,如果图片加载不出来,那么脚本应该把父 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/

相关文章:

flutter - 如何在 Flutter App 上设置自定义图片图标?使用应用图标

css - 在 RMarkdown 中,如何以 block 的形式获取 css 文件?

node.js - 连接 redis 时在 docker-compose 中出现错误 : conne

css - TailwindCSS : is it possible to remove a box

r - 将一列拆分为两列 : dataframes within a list

python - 如何将变量插入文件路径?

python - 列表的字典变成元组的元组的字典

r - 根据字符串匹配过滤列表

rust - 为什么不可变结构在移入向量时会变为可变结构?

rust - 为什么在堆栈中分配的值不会导致双自由指针?