How do I hide broken images in javascript?
I have my image inside an if statement:
if (item.image)
historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><开发者_运维技巧;img src="' + item.image +'" width="111px"/></a>';
You can use the onerror handler. In the inline form, it looks like this:
<img src="someimage.jpg" onerror="this.style.display='none';" />
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 error
event gets fired if loading fails.
But looking at your code, maybe the opposite approach makes most sense: Hide the <a>
by default, and show it in the onload
event of the image.
Abridged:
<a href=".." id="image228" style="display: none">
<img src="..." onload="this.parentNode.style.display = 'block'">
</a>
精彩评论