如何在 javascript 中隐藏损坏的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3675073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:53:48  来源:igfitidea点击:

How do I hide broken images in javascript?

javascripthtml

提问by jprim

I have my image inside an if statement:

我在 if 语句中有我的图像:

if (item.image)
   historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><img src="' + item.image +'" width="111px"/></a>';

回答by Piskvor left the building

You can use the onerror handler. In the inline form, it looks like this:

您可以使用 onerror 处理程序。在内联形式中,它看起来像这样:

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

回答by Pekka

As @piskvor says, actually loading the image in an img tag is the only way of finding out whether the URL is broken or not. The errorevent gets fired if loading fails.

正如@piskvor 所说,实际在 img 标签中加载图像是确定 URL 是否损坏的唯一方法。error如果加载失败,则触发该事件。

But looking at your code, maybe the opposite approach makes most sense: Hide the <a>by default, and show it in the onloadevent of the image.

但是查看您的代码,也许相反的方法最有意义:<a>默认情况下隐藏,并在onload出现图像时显示。

Abridged:

简略:

<a href=".." id="image228" style="display: none">
 <img src="..." onload="this.parentNode.style.display = 'block'">
</a>