触发onerror两次显示备用图像的备用图像
HTML: trigger onerror twice to display the alternate of the alternate image
我的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是。jpg或。png。此外,图像本身甚至可能不存在。所以我必须执行以下操作:
- 尝试加载image.jpg
- 加载image.png时出现错误
- 出现错误,显示未找到。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运行一个小函数来检查其他图像,如果他们没有加载显示已知存在的图像。
相关文章:
- 如何使用url加载程序在webpack中导入多个图像
- nodejs-expressjs上传图像并显示它们
- 使用JSP从服务器检索和显示图像
- 角度:在ng重复上切换图像
- 画廊图像未显示
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- Javascript排序的图像弹出窗口..可以't单独弹出
- 画布数据到图像
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 使图像在单击时展开到不大于浏览器
- Html页面上的多个Base64图像和平滑加载
- UIAutomation放大图像
- 使用javascript在Flash中加载外部图像
- 可以在这里为背景图像设置滤镜吗
- 使用modernizr为不支持webgl的浏览器提供备用背景图像
- 如果未找到 IMG SRC,则显示备用图像 - 挖空
- 在加载备用图像时显示另一个图像
- DIV - 备用背景图像
- 当主图像未加载(.net web表单)时,加载备用图像的最佳方式是什么
- 触发onerror两次显示备用图像的备用图像