使用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'; 
      } 
   });
});

 但是IE6的时候会出现不兼容的情况所以,最好的方法是在每个标签上增加 onerror = "this.src='/cqabc/images/huancun.gif'"属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值