【问题标题】:How to show image title if source image is not found using javascript or jQuery如果使用 javascript 或 jQuery 找不到源图像,如何显示图像标题
【发布时间】:2021-09-23 02:07:07
【问题描述】:

我想在图像损坏或在给定路径中找不到图像时显示图像标题。

到目前为止,我可以选择隐藏图像并将图像替换为默认图像

$('img').on("error", function() {
  $(this).attr('src', '/images/missing.png');
});

// Or, hide them
$("img").on("error", function() {
  $(this).hide();
});

但是,这不能满足我的要求。如果有人想在使用 JavaScript 或 jQuery 破坏图像时显示图像标题。请帮帮我。

【问题讨论】:

  • 你想在哪里显示标题
  • 使用 'alt' 属性来保存你想要的描述,它会显示你的信息以防图像由于某些故障而没有加载 - developer.mozilla.org/en-US/docs/Web/HTML/Element/img
  • Ire Aderinokun 用❤写的文章:bitsofco.de/styling-broken-images
  • 感谢您作为 cmets 分享您的想法,我已经破解了。谢谢
  • 如果您想考虑一个简单的 HTML/CSS 解决方案,请查看这个 CodePen:codepen.io/aequalsb/pen/poPRdBo 基本上...您可以使用 CSS 对图像进行样式化,就好像它是一个容器...如果图像坏了,看起来像一个普通的“盒子”

标签: javascript jquery css image


【解决方案1】:

使用replaceWith inside error 将您的图像标签替换为其他元素。

$('img').on("error", function() {
  var title = $(this).prop("title");
  $(this).replaceWith("<span>" + title + "</span>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://stackoverflow.com/testimg.jpg" title="Your title"></img>

【讨论】:

    【解决方案2】:

    $(document).ready(function() {
     
       
       $("img").on("error", function () {
        $(this).attr("src", "https://lh3.googleusercontent.com/-bRgqJ3P_4k8/AAAAAAAAAAI/AAAAAAAAAjQ/eYIXbdyNxKM/photo.jpg?sz=48");
    });
    });
    <!DOCTYPE html>
    <html>
    <head>
    <title>Try jQuery Online</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     
    </head>
    <body> 
     <img  
         src="/media/cc0-images/grapefruit-sl.jpg"
         alt="Grapefruit slice atop a pile of other slices">
    
    </body>
    </html>

    【讨论】:

    • 这没有回答 OP 的问题...... OP 专门询问如何显示“图像标题”
    • 嗨 aequalsb,到目前为止,我可以选择隐藏图像并用默认图像替换图像
    • 我不明白... OP 正在询问如何在链接断开的图像上“显示 IMG 标题”...而不是在链接断开的图像上“替换为默认图像”跨度>
    【解决方案3】:

    我找到了一个简单的方法来做到这一点,我们唯一需要做的就是将图像添加到 Div 中,这样我们就可以获得图像的父 DIV Id,并将标题附加到这个父 div 使用以下代码。

    var images = document.querySelectorAll('img');
    
    for (var i = 0; i < images.length; i++) {
      images[i].onerror = function() {
        $("#"+this.parentElement.id).append(this.title)
        this.style.display='none';
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-05
      • 1970-01-01
      • 2020-04-09
      • 2011-10-21
      • 2022-01-09
      • 2011-09-01
      • 2017-01-18
      • 1970-01-01
      • 2011-03-15
      相关资源
      最近更新 更多