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

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


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


当前回答

$(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。不过我估计过程会很缓慢。

你可以使用GitHub自己的fetch:

前端:https://github.com/github/fetch 或者在后端,一个Node.js版本:https://github.com/bitinn/node-fetch

fetch(url)
  .then(function(res) {
    if (res.status == '200') {
      return image;
    } else {
      return placeholder;
    }
  }

编辑:这个方法将取代XHR,据说已经在Chrome。对于将来阅读这篇文章的人来说,您可能不需要包含上述库。

这是一个蹩脚的技巧,但它几乎是可以保证的:

<img onerror="this.parentNode.removeChild(this);">

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

有时使用错误事件是不可行的,例如,当你试图在一个已经加载的页面上做一些事情时,比如当你通过控制台、bookmarklet或异步加载的脚本运行代码时。在这种情况下,检查img。和img。naturalHeight是0似乎做的把戏。

例如,这里有一个片段,从控制台重新加载所有损坏的图像:

$$("img").forEach(img => {
  if (!img.naturalWidth && !img.naturalHeight) {
    img.src = img.src;
  }
}