问题
I'm trying to figure out how to re-establish the img src if the image src path is invalid or no image is found. I have a dynamically created img src path that may sometimes be pointing to a directory with no actual images. In this case I need to change the src to img/missing.jpg
. I have done this with no luck:
$('.imgContainer').append( "<img id='pic' src='/dynamically/created/path/to/img.jpg'>" );
$('.imgContainer img#pic').load(function(){
if( $(this).width() == 0 && $(this).height() == 0 ){
$(this).attr({src: 'img/missing.jpg'})
.css({width:'100px', height:'100px'});
}
});
perhaps there is a better way to do this - but I do not know it...I tried using $(this).onerror = //some function
but couldn't figure out how to get that to work either.
any help would be greatly appreciated...
回答1:
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.
来源:https://stackoverflow.com/questions/6234148/jquery-re-establish-img-src-in-load-function