`
shao_lixin
  • 浏览: 50742 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

使用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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics