为什么其他所有浏览器(IE7、8、9、FF、Opera 和 Safari)都重复调用它,而 Chrome 只调用一次 img 元素的 onerror 事件?
有没有办法强制它再次重复 onerror 调用(在 Chrome 中)?
HTML:
<div id="thisWorks">
this works in Chrome. onerror event is called once.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://eatfrenzy.com/images/success-tick.png" />
</div>
<div id="thisDoesNotWork">
this does not work in Chrome. onerror event is not called twice.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://www.asdfjklasdfasdf.com/bogus2.png|http://eatfrenzy.com/images/success-tick.png" />
</div>
JavaScript:
function fixit(img)
{
var arrPhotos = img.getAttribute('rsrc').split('|');
// change the img src to the next available
img.setAttribute('src', arrPhotos.shift());
// now put back the image list (with one less) into the rsrc attr
img.setAttribute('rsrc', arrPhotos.join('|'));
return true;
}
编辑:
根据@Sunil D. 的评论,由于 initial fiddle 中的 www.asdfjklasdfasdf.com
域名无效,Chrome 没有发布新的查找。例如,我继续更改域名以匹配成功图片的域名,但文件名不同,所以它仍然是 404。这将证明它不是导致 Chrome 在第二次尝试中退出的无效域名。
编辑: 更新了 fiddle 并删除了对 jquery 的使用以简化事情并排除这种情况。
最佳答案
我已经尝试了上面提到的方法,setAttribute('src', null) 有一个副作用,即添加另一个请求。
最后,我用
setTimeout(function(){ imgElement.src = 'http://xxxx'; }, 0)
,这有效!
参见 jsfiddle例如。
关于html - 为什么 Chrome 的 img 元素的 onerror 事件只触发一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636397/