Home > Article > Web Front-end > Solution to the problem of binding error event to img in jquery
For example:
<img src = 'xxxx.jpg' > $('img').error(function(){ $(this).attr('src',"默认图片"); })
After testing, it was found that if the original image does not exist, the image on the page will keep flickering. How to solve this problem?
$(window).load(function() { $('img').each(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { this.src = 'http://www.tranism.com/weblog/images/broken.gif'; } }); });
I don’t understand very well. Does the original picture refer to xxxx.jpg? If your code’s default picture path is also wrong (that is, the default picture does not exist), it will enter a dead loop , so it keeps flashing and flashing because of the constant onerror
First check whether the image is loaded successfully, and then bind the event if it fails. And just replace it once.
<img src="xxxx.jpg" alt="" /><script>jQuery(document).ready(function(){ jQuery('img').each(function(){ var error = false; if (!this.complete) { error = true; } if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) { error = true; } if(error){ $(this).bind('error.replaceSrc',function(){ this.src = "default_image_here.png"; $(this).unbind('error.replaceSrc'); }).trigger('load'); } }); });</script>
The above is the detailed content of Solution to the problem of binding error event to img in jquery. For more information, please follow other related articles on the PHP Chinese website!