如果图像损坏,请隐藏li

时间:2013-11-24 02:40:03

标签: javascript jquery html css

我有一个图片列表,其中每张图片都包含在 li 中:

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

如果图像1.jpg被破坏,我怎么能隐藏整个 li ,好像它从未在DOM中存在过?

我找到了一些关于如何hide the image以及从another SO post学习我想要display:none的好js所以我不创建一个空行。但是我把这些放在一起很麻烦。

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

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

示例:

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

});

答案 2 :(得分:0)

使用jQuery,您可以将<li>设置为仅在<img>加载时加载。 Read along here.

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

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

答案 3 :(得分:0)

您可以使用:

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

on error处理图像,如果没有找到,则获取其id并从DOM中删除

相关问题