使用jquery给img绑定error事件的问题

 

先检查图片是否加载成功,然后如果失败的话再绑定事件。而且替换一次就好了。

<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>

 

 

 

$(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'; 
      } 
   });
});

http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images

 

 

 

 

 

posted @ 2013-09-26 11:03  赵小磊  阅读(708)  评论(0)    收藏  举报
回到头部