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

我如何使用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';
    }
  });
});

其他回答

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

lazyload();

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

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

更好的呼叫使用

jQuery(window).load(function(){
    $.imgReload();
});

因为使用文档。ready并不一定意味着图像被加载,只是HTML。因此,不需要延迟调用。

对于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;
    }}
 />

如果图像无法加载(例如,因为它不在提供的URL中),图像URL将被更改为默认值,

有关.error()的更多信息

美元(img)。On('错误',函数(e) { (美元)。attr(“src”、“broken.png”); });

如果有人像我一样,试图将错误事件附加到动态HTML img标记,我想指出的是,有一个陷阱:

显然,img错误事件不会在大多数浏览器中冒泡,这与标准的说法相反。

所以,像下面这样的代码是行不通的:

$(document).on('error', 'img', function () { ... })

希望这对其他人有所帮助。我希望我能在这个帖子里看到这个。但是,我没有。我把它加起来