简体   繁体   English

如何使用jQuery删除最后一个DIV?

[英]How to remove the last DIV using jQuery?

i have the following format : 我有以下格式:

<div id="container1">
<div id="post"> blah blah blah </div>
<div id="post"> blah blah blah </div>
<div id="post"> blah blah blah </div>
</div>

<div id="container2">
<div id="post"> blah blah blah </div>
<div id="post"> blah blah blah </div>
<div id="post"> blah blah blah </div>
</div>

I want a jQuery code to remove the last "post" DIV in the "container1" with a fading effect. 我想要一个jQuery代码来删除“container1”中最后一个具有淡化效果的“post”DIV。

Important : the "container1" does not have a specified "post" DIVs number. 重要提示:“container1”没有指定的“post”DIV编号。 so the code should just select the last "POST" div in the "container1" div. 所以代码应该只选择“container1”div中的最后一个“POST”div。

Thanks 谢谢

$('#container1 #post:last').fadeOut() would remove the last div with the ID "post" in "container1". $('#container1 #post:last').fadeOut()将删除“container1”中ID为“post”的最后一个div。

Also, like Gumbo said, IDs should be unique. 此外,就像Gumbo所说,ID应该是唯一的。 However, this jQuery code will still work. 但是,这个jQuery代码仍然有效。

IDs must be unique in a document. ID必须在文档中是唯一的。 So the selector #post will probably not work. 所以选择器#post可能不起作用。 But this should work anyway: 但无论如何这应该工作:

$("#container1").children("div[id=post]:last").fadeOut();

instead of .fadeout, you should use .remove to remove the element from the containing div. 而不是.fadeout,你应该使用.remove从包含div中删除元素。 Fadeout performs the fade transition, however the element still remains in the DOM and will be counted if manipulating the size of the div. Fadeout执行淡入淡出过渡,但是元素仍然保留在DOM中,并且在操作div的大小时将被计数。

To fine tune the fadeout timing you can use hide instead: 要微调淡出时间,您可以使用隐藏:

$(document).ready(function() {
        $("#container2 div:last").hide(2000);
    });
$("#container1").children("div[id=post]:last").remove();

将删除最后一个div等等,直到所有div被删除。

This fades it out and also removes it from the DOM 这会将其淡出并将其从DOM中删除

$('#container1 #post:last').fadeOut('slow',function(){
    $(this).remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM