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

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


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


当前回答

这里有一个独立的解决方案:

$(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';
    }
  });
});

其他回答

对于React开发者:

<img 
    src={"https://urlto/yourimage.png"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load
    width={200} 
    alt={"Image"} 
    onError={(event) => {
       event.target.onerror = "";
       event.target.src = "anyplaceholderimageUrlorPath"
       return true;
    }}
 />

我找不到适合我需要的脚本,所以我做了一个递归函数来检查损坏的图像,并尝试每四秒重新加载它们,直到它们修复。

我将它限制为10次尝试,因为如果它没有加载,那么图像可能不会出现在服务器上,函数将进入一个无限循环。不过我仍在测试中。请随意调整它:)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});

我使用惰性加载,必须这样做,以使它正常工作:

lazyload();

var errorURL = "https://example.com/thisimageexist.png";

$(document).ready(function () {
  $('[data-src]').on("error", function () {
    $(this).attr('src', errorURL);
  });
});

我在看另一个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} />;
    );
}

使用JavaScript处理图像的onError事件以重新分配其源:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

或者没有JavaScript函数:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

下面的兼容性表列出了支持错误功能的浏览器:

http://www.quirksmode.org/dom/events/error.html