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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2164415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:02:43  来源:igfitidea点击:

How to remove the last DIV using jQuery?

javascriptjquery

提问by Ryan

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. so the code should just select the last "POST" div in the "container1" div.

重要提示:“container1”没有指定的“post”DIV 编号。所以代码应该只选择“container1”div中的最后一个“POST”div。

Thanks

谢谢

回答by twernt

$('#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. However, this jQuery code will still work.

另外,就像 Gumbo 所说的,ID 应该是唯一的。但是,这个 jQuery 代码仍然有效。

回答by Gumbo

IDs must be unique in a document.So the selector #postwill probably not work. But this should work anyway:

ID 在文档中必须是唯一的。所以选择器#post可能不起作用。但这无论如何都应该有效:

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

回答by Naren

instead of .fadeout, you should use .remove to remove the element from the containing 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,您应该使用 .remove 从包含的 div 中删除元素。Fadeout 执行淡入淡出过渡,但是元素仍然保留在 DOM 中,如果操作 div 的大小,将被计数。

回答by Genady Sergeev

To fine tune the fadeout timing you can use hide instead:

要微调淡出时间,您可以使用 hide 代替:

$(document).ready(function() {
        $("#container2 div:last").hide(2000);
    });

回答by Captain Sparrow

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

will remove last div and so on till all div get removed.

将删除最后一个 div,依此类推,直到所有 div 被删除。

回答by Fabrizio

This fades it out and also removes it from the DOM

这会使其淡出并将其从 DOM 中删除

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