我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
当前回答
jQuery 1.8
// If missing.png is missing, it is replaced by replacement.png
$( "img" )
.error(function() {
$( this ).attr( "src", "replacement.png" );
})
.attr( "src", "missing.png" );
jQuery 3
// If missing.png is missing, it is replaced by replacement.png
$( "img" )
.on("error", function() {
$( this ).attr( "src", "replacement.png" );
})
.attr( "src", "missing.png" );
参考
其他回答
我发现这是最好的工作方式,如果任何图像第一次加载失败,它将完全从DOM中删除。执行console.clear()可以保持控制台窗口干净,因为404错误不能被try/catch块忽略。
$('img').one('error', function(err) {
// console.log(JSON.stringify(err, null, 4))
$(this).remove()
console.clear()
})
$(window).bind('load', function() {
$('img').each(function() {
if( (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0)
|| this.readyState == 'uninitialized' ) {
$(this).attr('src', 'missing.jpg');
}
});
});
来源:http://www.developria.com/2009/03/jquery-quickie--broken-images.html
我不确定是否有更好的方法,但我可以想到一个hack来获得它-你可以Ajax post到img URL,并解析响应,看看图像是否真的回来了。如果返回404或其他错误,则更换img。不过我估计过程会很缓慢。
CoffeeScript变体:
我这样做是为了修复Turbolinks的一个问题,该问题有时会导致.error()方法在Firefox中被引发,即使图像确实存在。
$("img").error ->
e = $(@).get 0
$(@).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)
这是一个蹩脚的技巧,但它几乎是可以保证的:
<img onerror="this.parentNode.removeChild(this);">