【问题标题】:Hide image when the src is unknownsrc 未知时隐藏图像
【发布时间】:2018-10-24 17:23:45
【问题描述】:

我正在尝试在 WordPress 中隐藏没有 src 的图像。

下面是前端显示的图片代码

<img src="[custom-gallery-image-01]" class="galimage" height="300" width="580"/>

用来隐藏图片的JS

<script type="text/javascript">
$(document).ready(function() {
   $(".galimage").each(function() {
        var atr = $(this).attr("src"); 
        if(atr == "") {
            $(this).addClass("hidegalimage");
        } else {
            $(this).removeClass("hidegalimage");
        }
    });
});
</script>

CSS

.hidegalimage {
display:none;
}

但我仍然可以看到损坏的图像图标和图像边框。查看JSFiddle。有人可以解决我的问题或给我建议如何隐藏图像吗?

非常感谢

【问题讨论】:

  • disply:none; 拼写在编程中很重要。
  • 我的错,我在 JSFiddle 中修复了它,但它仍然显示损坏的图像
  • 假设如果没有找到图像,[custom-gallery-image-01] 短代码会被空字符串替换,那么您的代码确实有效:jsfiddle.net/ukc78mrm
  • 在您的代码中,您要查看 src 是否等于空白字符串。但是在您的图像标签中,您的字符串设置为 [custom-gallery-image-01] 的文字字符串。当函数运行时,它不会设置你的类,因为 src 不是空的。
  • @cabrerahector 谢谢!

标签: javascript html css wordpress


【解决方案1】:

改用 CSS 会更优雅,不需要 Javascript,假设坏的 srcs 在你的 HTML 中以 [ 开头: 是空字符串:

.galimage[src=""] {
  display:none;
}
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>
<img src="" class="galimage" height="300" width="580"/>
<img src="https://www.gravatar.com/avatar/b3559198b8028bd3d8e82c00d16d2e10?s=32&d=identicon&r=PG&f=1" class="galimage" height="300" width="580"/>

【讨论】:

  • @CertainPerformance 谢谢大家!这就像一个魅力。当我检查没有 src 的元素时,它显示 src(unknown)。但是在添加 CSS 之后,效果很好。
  • @cale_b 谢谢,我也不这么认为
  • 非常感谢您的时间、努力和知识!
【解决方案2】:

使用 jquery

$("img").error(function(){
        $(this).hide();
});

或者

$("img").error(function (){ 
    $(this).hide();
    // or $(this).css({'display','none'}); 
});

【讨论】:

    【解决方案3】:
    • 不需要 CSS 替代品

    您可以使用它,但这并没有隐藏它从页面中的删除(DOM):

    <img id='any' src="https://invalid.com" onerror="document.getElementById(this.id).remove()" >
    

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2013-04-02
      • 2013-09-15
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2011-03-15
      • 2014-06-02
      • 2012-05-13
      相关资源
      最近更新 更多