jQuery的第n个孩子去除

问题描述:

我有3个图像jQuery的第n个孩子去除

<img> 
<img> 
<img> 

当我删除的图像

$('img:nth-child(1)').remove(); 

,然后再添一个。

$('.hero .trim').append($img); 

然后尝试删除第一个再次

$('img:nth-child(1)').remove(); 

它不工作。我怎样才能使这个工作,所以新的形象是第一个孩子?

编辑全码...

function completeIt() { 
    $('.hero .trim img:nth-child(1)').remove(); 
}; 

if(this.talentClick == false) { 

//$('.hero .trim img').append('<img>').attr('src', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-mobile', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-tablet', '/img/headers/'+deptname+'-header-tablet.jpg').attr('data-desktop', '/img/headers/'+deptname+'-header.jpg') 




let img = ''; 
let width= $(document).width(); 



var $img = $('<img />').attr('src', '/img/headers/'+deptname+'-header.jpg').attr('data-mobile', '/img/headers/'+deptname+'-header-mobile.jpg').attr('data-tablet', '/img/headers/'+deptname+'-header-tablet.jpg').attr('data-desktop', '/img/headers/'+deptname+'-header.jpg') 

$('.hero .trim').append($img); 


let firstimgheight = $('.hero .trim img:nth-child(1)').height(); 
let secondimgheight = $('.hero .trim img:nth-child(2)').height(); 


console.log($('.hero .trim img:nth-child(1)')); 

tl.to($('.hero .trim img:nth-child(1)'), 0.2, {css:{marginTop: -firstimgheight+"px"}}) 

。为($(),1, '修剪。 '{CSS:{高度:secondimgheight +' 像素'}});

+0

看看事件委托,你添加的元素不会被jquery看到。 – Mihai

+0

这仅用于说明目的 - 有一个容器。这更多的是关于Jquery在删除后如何对待它的问题。 – LeBlaireau

+0

问题是您的代码*会删除第一张图片,但第一张图片不是您想要的特定图片? – apsillers

如果您想让新图像成为第一个子图像,请使用prepend而不是append(单击第一个按钮以删除第一个子图像并添加新图像,然后单击第二个图标删除新添加的图像):

$(function() { 
 
    var $img = '<img src="http://placehold.it/250x250/000/fff" />'; 
 
    $('button.one').click(function() { 
 
    $('img:nth-child(1)').remove(); 
 
    $('.hero .trim').prepend($img); 
 
    }); 
 
    $('button.two').click(function() { 
 
    $('img:nth-child(1)').remove(); 
 
    }); 
 
});
button { 
 
display:inline-block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="one">Button 1</button> 
 
<button class="two">Button 2</button> 
 
<div class="hero"> 
 
    <div class="trim"> 
 
    <img src="http://placehold.it/250x250/fff/ccc" /> 
 
    <img src="http://placehold.it/250x250/ccc/aaa" /> 
 
    <img src="http://placehold.it/250x250/eee/ccc" /> 
 
    </div> 
 
</div>

使用您的标记的示例见https://jsbin.com/fixelobeno/edit?html,output

<div class="x"> 
    <img class="1"> 
    <img class="2"> 
    <img class="3"> 
    </div> 

    <script> 
    $('img:nth-child(1)').remove(); 
    $('.x').append("<img class='new'>"); 
    $('img:nth-child(1)').remove(); 
    </script> 

的第一个孩子被删除,那么新的标签附加到div,并在年底的新的第一个项目被删除。

为了简单起见,我们假设这些图像的父div具有id“main”。 您需要使用insertBefore而不是append。例如:

要删除第n IMG:

$("#main img:nth-child(1)").remove(); 

先添加新的IMG:

$("<img src='' />").insertBefore("#main img:nth-child(1)"); 

append增加了项目的子标签的最后位置。 insertBefore在你指定的地方添加它。