jquery re-establish img src in .load() function

喜欢而已 提交于 2019-12-06 10:48:29

The key to the problem is that the 'load' event only fires on images when the image is successfully loaded - so if you specify an invalid path, the load event will never take place. You want the 'error' handler instead, like this:

var img = $("<img id='pic' src='/dynamically/created/path/to/img.jpg'>")
 .error(function(){
        $(this).attr({src: 'img/missing.jpg'})
               .css({width:'100px', height:'100px'});
 })
 .appendTo('.imgContainer');

I've streamlined your code a little bit - so the order is: create the image element, bind the error event handler, then append to the document. I don't know if it makes any practical difference, but it seems to make more sense to set the handlers before the image has a chance to start loading (otherwise the load could theoretically happen before your event has been assigned).

Also, your check for width== 0 and height == 0 won't work in all browsers. Chrome and Safari both give you the width and height of the 'broken image' icon they show: 18x18px.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!