【问题标题】:HTML: trigger onerror twice to display the alternate of the alternate imageHTML:触发onerror两次以显示替代图像的替代
【发布时间】:2013-06-01 17:46:48
【问题描述】:

我的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是 .jpg 或 .png。此外,图像本身甚至可能不存在。所以我必须执行以下操作:

  1. 尝试加载 image.jpg
  2. 错误,尝试加载 image.png
  3. 出错,显示 notfound.jpg

我写了以下代码:

<img src=image.jpg onerror="this.onerror=null; this.src=image.png;">

但是 "this.onerror=null" 只会阻止 onerror 进入无限循环。当再次触发 onerror 时,如何加载替代图像的替代图像“notfound.jpg”?

【问题讨论】:

    标签: javascript html image onerror


    【解决方案1】:

    这里我有我会用 jquery 做的事情。我问你是否可以,你没有回复。

    原来如此。

    这是标准的 html:

    <img src=image.jpg alt="" />
    

    这将是附加到它的 jquery:

    $('img').on('error', function () {
        var $this = $(this);
        // ajax with type 'HEAD' checks to see if the file exists
        $.ajax({
            url: 'image.png', //place alternate img link here
            type: 'HEAD',
            success: function () {
                //if success place alternate image url into image
                $this.prop('src', 'image.png');
            },
            error: function () {
                //if error place notfound image url into image
                $this.prop('src', 'notfound.jpg');
            }
        });
    });
    

    我让它在不同的环境中工作,但它显示了最终产品:http://jsfiddle.net/6nFdr/

    【讨论】:

    • 谢谢!我试图避免使用 jquery,但似乎这是唯一的选择。
    【解决方案2】:

    在onerror设置图片src后返回false。

    示例:

    <img src="fake.png" onerror="this.src='http://www.gravatar.com/avatar/9950cb3a6bdc0e10b1260135bd145e77?s=32&d=identicon&r=PG'; return false;">
    

    演示:http://jsfiddle.net/rlemon/SKtVg/

    顺便说一句,您应该避免使用内联 javascript。并不是说它不正确,只是不太理想。 如果你没有使用内联 js,你可以让 onerror 运行一个小函数来检查其他图像,如果它们没有加载,则显示已知存在的图像。

    【讨论】:

    • 您能解释一下这有什么帮助吗? “notfound.jpg”如何显示?
    猜你喜欢
    • 2021-02-11
    • 2012-06-02
    • 1970-01-01
    • 2021-12-29
    • 2021-10-12
    • 1970-01-01
    • 2013-11-20
    • 2013-04-27
    • 1970-01-01
    相关资源
    最近更新 更多