onerror
处理程序处理图像:<li><a href='http://www.so.com'>
<img src='http://www.so.com/1.jpg' onerror='hideContainer(this)'>
</a></li>
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").hide();
}
// this function must be in the global scope
function hideContainer(el) {
$(el).closest("li").remove();
}
onerror
处理程序(唯一可靠的放置位置),那么可以最初隐藏图像,然后在运行jQuery时检查.complete
,如果图像尚未完成,则安装.load()
处理程序,如下所示:/* use some more specific selector than this */
li {display: none;}
jQuery:
$("li img").each(function() {
if (this.complete) {
// img already loaded successfully, show it
$(this).closest("li").show();
} else {
// not loaded yet so install a .load handler to see if it loads
$(this).load(function() {
// loaded successfully so show it
$(this).closest("li").show();
});
}
});
<img id='any' src="https://invalid.com" onerror="document.getElementById(this.id).remove()" >
在出现错误时,处理图像,如果找不到则获取其ID并从DOM中删除
$('img').error(function(event) {
$(this).closest('li').hide();
});
this
不是jQuery对象。3)在运行jQuery安装错误处理程序之前可能会发生错误。 - jfriend00<li>
仅在<img>
加载时才加载。在此处阅读更多内容。
HTML起始代码为:
<li style="display: none;"><a href='http://www.so.com'><img src='http://www.so.com/1.jpg' id="imgOne" class="imgSet"></a></li>
如果它是一组中的一部分,可以给它一个类;如果它非常具体且您只想要那个,请给它一个ID;如果您想要选择页面上的所有图像,则可以选择所有图像。在我的示例中,我将使用类来将其作为一组进行选择。
jQuery:
$('.imgSet').load(function() {
$(this).parents('li').show();
});
基本上在图片加载完成之前它是隐藏的。
.load()
处理程序之前加载(例如,如果图像在缓存中),因此您将错过加载事件。 - jfriend00.load()
事件,这很容易发生在图片被缓存的情况下,那么你将永远不会显示成功加载的图片。这是在DOM解析之后安装事件处理程序的常见问题。有些事件可能已经在你安装事件处理程序之前发生了。 - jfriend00