我所处的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是 .jpg 或 .png。此外,图像本身可能根本不存在。所以我必须执行以下操作:
- 尝试加载 image.jpg
- 出现错误,尝试加载 image.png
- 出错时,显示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/