javascript - HTML:触发onerror两次以显示替代图像的替代

标签 javascript html image onerror

我所处的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是 .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”的替代图像?

最佳答案

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

关于javascript - HTML:触发onerror两次以显示替代图像的替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875485/

相关文章:

javascript - 在 JavaScript 中获取图像数据 URL?

html - 与其他图像相比图像的响应尺寸

javascript - Protractor 定位器 by.repeater 使用 'contains' 而不是 'equals'

javascript - 在 KeyUp 和粘贴事件上限制 AJAX 请求

javascript - 选择子菜单后切换菜单

jquery - Jquery如何获取表格的高度

Javascript - 操作现有 JSON 字符串中的数组结构

javascript - 通过包含在另一个数组中的对象属性对 Javascript 数组进行排序

javascript - 如何让 JavaScript 计算显示在文本框中

android - ARToolkit for Android 是否能够识别图像而非视频中的标记?