删除所有图像,但首先在div中删除

时间:2016-03-01 07:16:05

标签: jquery html

采取以下示例

<div id="blog">
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
    </div>
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
    </div>
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
        <img src="img.png" alt="REMOVE this one"/>
    </div>
</div>

显然我想删除alt所在的图像(尽管生产方式不同)&#34;删除这个&#34;

我尝试过:

$('#blog .postContent img').slice(1).remove(); // AND
$('#blog .postContent img').not(':first').remove();

结果:

<div id="blog">
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
    </div>
    <div class="postContent">
    </div>
    <div class="postContent">
    </div>
</div>

但是我想要的结果是:

<div id="blog">
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
    </div>
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
    </div>
    <div class="postContent">
        <img src="img.png" alt="Keep this one"/>
    </div>
</div>

我错过了我确定应该非常简单的事情,非常感谢任何指针

3 个答案:

答案 0 :(得分:2)

尝试使用:not()选择器和:first-child选择器

$('#blog .postContent img:not(:first-child)').remove();

DEMO

或者您可以使用简单的css来实现此目的,

#blog .postContent img:not(:first-child){
  display:none;
}

DEMO

答案 1 :(得分:1)

纯CSS:

.postContent img:nth-child(n+2) {
  display: none;
}

<强> jsFiddle Demo

jQuery版本:

$('.postContent').each(function(){
$(this).children('img:nth-child(n+2)').remove();
});

<强> jsFiddle Demo

答案 2 :(得分:1)

试试这个。first-of-type

$('#blog .postContent img').not('img:first-of-type').remove()