为图片指定加载失败时显示默认图片,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';
}
});
})