JS Hiding Broken Images Within Class

和自甴很熟 提交于 2021-01-27 20:32:35

问题


I understand how to hide images if they're as followed,

<img src=""......>

However, I'm having problems as I know nothing about JS on how to hide broken images if they're like this,

<div class="lx-g3-f" >
  <div class="lx-gallery" data-bg="image_url" alt="alt text" referrerpolicy="no-referrer" title="something title">
  <div class="lx-gallery-title" >
    <h3><a href='something_img_url' referrerpolicy="no-referrer">click here!</a></h3>
  </div>
</div>              

How can I make the following work when img doesn't exist.

$("img").on("error", function() {
    $(this).closest('.lx-g3-f').hide();
});

回答1:


Not trivial

Try

$(function() {
  $("[data-bg]").each(function() {
    const $parent = $(this).closest(".lx-g3-f")
    const img = new Image();
    img.onerror=function() {
      $parent.hide();
    }
    img.src=$(this).data("bg")
  })
})


来源:https://stackoverflow.com/questions/64678812/js-hiding-broken-images-within-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!