Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-06-27 11:23:01
Original
2383 people have browsed it

For example:

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

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

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;; 
      } 
   });
});
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!