我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。

我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?


—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。


当前回答

我相信这就是你想要的:jQuery。预加载

下面是演示中的示例代码,你指定加载和未找到的图像,你就全部设置好了:

jQuery('#images img').preload({
  placeholder:'placeholder.jpg',
  notFound:'notfound.jpg'
});

其他回答

我也有同样的问题。这个代码在我的案子上很有效。

// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});

我使用内置的错误处理程序:

$("img").error(function () {
    $(this).unbind("error").attr("src", "broken.gif");
});

编辑:error()方法在jquery 1.8及更高版本中已弃用。相反,你应该使用.on("error"):

$("img").on("error", function () {
    $(this).attr("src", "broken.gif");
});

我在看另一个SO帖子的时候发现了这个帖子。下面是我在那里给出的答案的副本。

我知道这是一个老帖子,但React已经变得流行起来,也许使用React的人会来这里寻找同样问题的答案。

所以,如果你正在使用React,你可以像下面这样做,这是由React团队的Ben Alpert提供的原始答案

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

我不确定是否有更好的方法,但我可以想到一个hack来获得它-你可以Ajax post到img URL,并解析响应,看看图像是否真的回来了。如果返回404或其他错误,则更换img。不过我估计过程会很缓慢。

通过使用Prestaul的答案,我添加了一些检查,我更喜欢使用jQuery的方式。

<img src="image1.png" onerror="imgError(this,1);"/>
<img src="image2.png" onerror="imgError(this,2);"/>

function imgError(image, type) {
    if (typeof jQuery !== 'undefined') {
       var imgWidth=$(image).attr("width");
       var imgHeight=$(image).attr("height");

        // Type 1 puts a placeholder image
        // Type 2 hides img tag
        if (type == 1) {
            if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
                $(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
            } else {
               $(image).attr("src", "http://lorempixel.com/200/200/");
            }
        } else if (type == 2) {
            $(image).hide();
        }
    }
    return true;
}