触发onerror两次显示备用图像的备用图像

HTML: trigger onerror twice to display the alternate of the alternate image

本文关键字:备用 图像 显示 两次 onerror 触发      更新时间:2023-09-26

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

  1. 尝试加载image.jpg
  2. 加载image.png时出现错误
  3. 出现错误,显示未找到。jpg
我写了下面的代码:
<img src=image.jpg onerror="this.onerror=null; this.src=image.png;">

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

这里我将使用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/

在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运行一个小函数来检查其他图像,如果他们没有加载显示已知存在的图像。