Home  >  Article  >  Web Front-end  >  Solution to the problem of binding error event to img in jquery

Solution to the problem of binding error event to img in jquery

黄舟
黄舟Original
2017-06-27 11:23:012454browse

For example:

<img src = &#39;xxxx.jpg&#39; >

$(&#39;img&#39;).error(function(){
    $(this).attr(&#39;src&#39;,"默认图片");
})

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() { 
  $(&#39;img&#39;).each(function() {    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { 
      this.src = &#39;http://www.tranism.com/weblog/images/broken.gif&#39;; 
      } 
   });
});

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(&#39;img&#39;).each(function(){        var error = false;        if (!this.complete) {
            error = true;
        }        if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) {
            error = true;
        }        if(error){
            $(this).bind(&#39;error.replaceSrc&#39;,function(){                this.src = "default_image_here.png";

                $(this).unbind(&#39;error.replaceSrc&#39;);
            }).trigger(&#39;load&#39;);
        }
    });
});</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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn