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

前端之家收集整理的这篇文章主要介绍了html – 为什么Chrome的img元素的onerror事件只触发一次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当所有其他浏览器(IE7,8,9,FF,Opera和Safari)都重复调用它时,为什么Chrome只调用img元素的onerror事件?

有没有办法强制它再次重复攻击(在Chrome中)?

jsfiddle

HTML:

  1. <div id="thisWorks">
  2. this works in Chrome. onerror event is called once.
  3. <img src="http://www.asdfjklasdfasdf.com/bogus1.png"
  4. onerror="fixit(this);"
  5. rsrc="http://eatfrenzy.com/images/success-tick.png" />
  6. </div>
  7.  
  8. <div id="thisDoesNotWork">
  9. this does not work in Chrome. onerror event is not called twice.
  10. <img src="http://www.asdfjklasdfasdf.com/bogus1.png"
  11. onerror="fixit(this);"
  12. rsrc="http://www.asdfjklasdfasdf.com/bogus2.png|http://eatfrenzy.com/images/success-tick.png" />
  13. </div>

JAVASCRIPT:

  1. function fixit(img)
  2. {
  3. var arrPhotos = img.getAttribute('rsrc').split('|');
  4.  
  5. // change the img src to the next available
  6. img.setAttribute('src',arrPhotos.shift());
  7.  
  8. // now put back the image list (with one less) into the rsrc attr
  9. img.setAttribute('rsrc',arrPhotos.join('|'));
  10.  
  11. return true;
  12. }

编辑:
根据@Sunil D.关于Chrome由于initial fiddle示例中www.asdfjklasdfasdf.com域名无效而未发布新查询评论,我继续更改域名以匹配成功图片的域名,但是不同的文件名所以它仍然是404.这将证明它不是无效的域名导致Chrome在第二次尝试时纾困.

编辑:
更新了小提琴,并将jquery的使用简单地删除,并将其排除在外.

解决方法

我尝试过上面提到的方法,setAttribute(‘src’,null)有副作用,即添加另一个请求.

最后,我用

  1. setTimeout(function(){ imgElement.src = 'http://xxxx'; },0)

,这个有效!

例如,请参见jsfiddle.

猜你在找的HTML相关文章