如果损坏图像,隐藏li

Hide li if broken image

本文关键字:隐藏 li 图像 损坏 如果      更新时间:2023-10-03

我有一个图像列表,其中每个图像都封装在li:中

<li><a href='http://www.so.com'><img src='http://www.so.com/1.jpg'></a></li>

如果图像1.jpg被破坏,就好像它从未存在于DOM中一样,我如何隐藏整个li

我发现了一些关于如何隐藏图像的好js,并从另一篇SO帖子中了解到我想要display:none,这样我就不会创建空行。但我很难把这些放在一起。

您可以对图像使用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();
}

或者,如果你真的想要它,你甚至可以把它删除,就好像它从未存在于DOM中一样:

// this function must be in the global scope
function hideContainer(el) {
    $(el).closest("li").remove();
}

如果你不想在HTML中放置onerror处理程序(这是你唯一可以放置它的可靠位置),那么你可以在最初隐藏图像,然后在jQuery运行时检查.complete,如果图像还没有完成,那么安装一个.load()处理程序,如下所示:

CSS:

/* 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();
        });
    }
});

在jQuery中有.error事件处理程序http://api.jquery.com/error/.

示例:

$('img').error(function(event) {
   $(this).closest('li').hide();     
});

使用jQuery,您可以将<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();
});

基本上它是隐藏的,直到图像加载。

您可以使用这个:

<img id='any' src="https://invalid.com" onerror="document.getElementById(this.id).remove()" >

错误时处理图像,如果找不到,则获取其id并将其从DOM 中删除