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

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

如:

<img src = 'xxxx.jpg' >

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

经过测试发现,如果原始图片不存在的话,页面上的图片就会一直闪烁,如何解决这个问题?


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


http://www.cnblogs.com/MaxIE/archive/2010/10/19/1855462.html


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

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

参考


没太懂,原始图片是指xxxx.jpg吗?你这个代码如果默认图片路径也是错误的话(也就是默认图片也不存在)就进入死循环了,所以一直闪啊闪,因为不断的onerror

【热门文章】
【热门文章】