Javascript HTML:触发OneError两次以显示备用图像的备用图像
我所处的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是.jpg或.png。此外,图像本身甚至可能不存在。因此,我必须执行以下操作:Javascript HTML:触发OneError两次以显示备用图像的备用图像,javascript,html,image,onerror,Javascript,Html,Image,Onerror,我所处的情况是,我知道图像的名称,但不知道确切的扩展名。扩展名可以是.jpg或.png。此外,图像本身甚至可能不存在。因此,我必须执行以下操作: 尝试加载image.jpg OneError,尝试加载image.png Onerror,display notfound.jpg 我编写了以下代码: <img src=image.jpg onerror="this.onerror=null; this.src=image.png;"> 但是“this.onerror=null”只能
<img src=image.jpg onerror="this.onerror=null; this.src=image.png;">
但是“this.onerror=null”只能阻止onerror进入无限循环。当onerror再次触发时,如何加载替代映像“notfound.jpg”的替代映像?在onerror中,设置映像src后返回false 例如:
<img src="fake.png" onerror="this.src='http://www.gravatar.com/avatar/9950cb3a6bdc0e10b1260135bd145e77?s=32&d=identicon&r=PG'; return false;">
演示:
顺便说一句,您应该避免内联javascript。这并不是说它不正确,只是不太理想。
如果您没有使用内联js,您可以让OneError运行一个小函数来检查其他图像,如果它们没有加载,则显示已知存在的图像 这里我有了使用jquery应该做的事情。我问你是否可以,你没有回答 就是这样 以下是标准html:
<img src=image.jpg alt="" />
在这里,我让它在不同的环境中工作,但它显示了最终产品:您能解释一下这有什么帮助吗?“notfound.jpg”是如何显示的?谢谢!我试图避免使用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');
}
});
});