您的位置:首页 > 其它

图片onerror事件,为图片加载指定默认图片

2013-07-31 09:00 190 查看
为图片指定加载失败时显示默认图片,js输出的img对象,onerror是事件,不是属性,所以这样写是不起作用的:
var img = $(document.createElement("IMG"));
    img.attr({
        "src": imgs[idx],
        "alt": tips[idx],
        "onerror":"this.src='" + NoPicPath +"'"
    }).appendTo(div);

应该是绑定事件:
    //图片加载失败时,加载默认图片
    $('img').error(function () {
      $(this).attr('src', NoPicPath);
    });
    if ($.browser.msie && $.browser.version < 9) {
        $('img').each(function () {
           $(this).attr('src', $(this).attr('src'));
        });
    }

参考:http://www.paulund.co.uk/handle-image-loading-errors-with-jquery

2017-3-15 更新:jquery 3+版本去掉了error事件,可以用下面方式绑定

    $(function () {

        $('img').each(function () {

            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

                this.src = '/uploadfiles/nophoto.jpg';

            }

        }); 

    })
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: