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

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


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


当前回答

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

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

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

其他回答

当OP正在寻找替换SRC时,我相信许多人遇到这个问题可能只希望隐藏损坏的图像,在这种情况下,这个简单的解决方案对我来说非常有用。

使用内联JavaScript:

<img src="img.jpg" onerror="this.style.display='none';"/>

使用外部JavaScript:

var images = document.querySelectorAll('img'); For (var I = 0;I < images.length;我+ +){ 图像[我]。Onerror = function() { this.style.display = '没有'; } } <img src='img.jpg' />

使用现代外部JavaScript:

document.querySelectorAll('img').forEach((img) => { img。Onerror = function() { This.style.display = 'none'; } }); <img src='img.jpg' />

参见浏览器对NodeList的支持。forEach和arrow函数。

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

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

你可以使用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。对于将来阅读这篇文章的人来说,您可能不需要包含上述库。

CoffeeScript变体:

我这样做是为了修复Turbolinks的一个问题,该问题有时会导致.error()方法在Firefox中被引发,即使图像确实存在。

$("img").error ->
  e = $(@).get 0
  $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)

多年来,这一直困扰着我。我的CSS修复在img上设置了一个背景图像。当动态图像src没有加载到前景时,img的bg上有一个占位符。如果你的图片有一个默认大小(例如高度,最小高度,宽度和/或最小宽度),这是有效的。

你会看到破碎的图像图标,但这是一种改进。成功测试到IE9。iOS、Safari和Chrome甚至都不会显示坏掉的图标。

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
}

添加一个小动画,让src在没有背景闪烁的情况下加载。Chrome浏览器在后台可以平滑淡出,但桌面版Safari浏览器却不能。

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
  animation: fadein 1s;                     
}

@keyframes fadein {
  0%   { opacity: 0.0; }
  50%  { opacity: 0.5; }
  100% { opacity: 1.0; }
}

.dynamicContainer img { background: url('https://picsum.photos/id/237/200'); background-size: contain; animation: fadein 1s; } @keyframes fadein { 0% { opacity: 0.0; } 50% { opacity: 0.5; } 100% { opacity: 1.0; } } img { /* must define dimensions */ width: 200px; height: 200px; min-width: 200px; min-height: 200px; /* hides broken text */ color: transparent; /* optional css below here */ display: block; border: .2em solid black; border-radius: 1em; margin: 1em; } <div class="dynamicContainer"> <img src="https://picsum.photos/200" alt="Found image" /> <img src="https://picsumx.photos/200" alt="Not found image" /> </div>