我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。
我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?
—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。
当前回答
如果图像无法加载(例如,因为它不在提供的URL中),图像URL将被更改为默认值,
有关.error()的更多信息
美元(img)。On('错误',函数(e) { (美元)。attr(“src”、“broken.png”); });
其他回答
这里有一个独立的解决方案:
$(window).load(function() {
$('img').each(function() {
if ( !this.complete
|| typeof this.naturalWidth == "undefined"
|| this.naturalWidth == 0 ) {
// image was broken, replace with your new image
this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
}
});
});
我不确定是否有更好的方法,但我可以想到一个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)
$(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
如果你已经用innerHTML插入了img,比如:$("div")。innerHTML = <img src="wrong-uri">,你可以加载另一个图像,如果它失败了,例如:
<script>
function imgError(img) {
img.error="";
img.src="valid-uri";
}
</script>
<img src="wrong-uri" onerror="javascript:imgError(this)">
为什么javascript: _needed?因为通过innerHTML中的脚本标记注入DOM的脚本在注入时不会运行,所以必须显式。