html - 为什么 Chrome 的 img 元素的 onerror 事件只触发一次?

标签 html image google-chrome events onerror

为什么其他所有浏览器(IE7、8、9、FF、Opera 和 Safari)都重复调用它,而 Chrome 只调用一次 img 元素的 onerror 事件?

有没有办法强制它再次重复 onerror 调用(在 Chrome 中)?

jsfiddle

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/

相关文章:

html - 背景图片网址

html - 如何垂直居中图像并使其填充可用宽度

css - 仅在 Chrome/Safari 中文本重叠 float 图像

javascript - 在 try/catch block 中无法捕获 Chrome 的 'Cannot Load Local Resource' 错误

image - 如何在 React Native 中将图像 URI 转换为 Byte[](字节数组)

javascript - jQuery 卸载在 Chrome 中不起作用

javascript - 抓取拖放的项目作为 <div> 的子节点

html - 为什么内部 DIV 不可见

html - 导航栏不固定

html - 将 HTML 元素放置在具有动态大小的图像上