使用 jQuery 删除父 div 中第一个 div 的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6543461/
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
What's the best way to remove first div inside a parent div using jQuery?
提问by enormace
I have the following markup:
我有以下标记:
<div id="parent">
<div id="divToRemove">
</div>
</div>
And I have the following jQuery to remove the first div which works fine:
我有以下 jQuery 来删除第一个工作正常的 div:
$('#parent').find('div').remove();
Is this the best way to remove the first component? Or is it more efficient to use selectors? An example would be great!
这是删除第一个组件的最佳方法吗?还是使用选择器更有效?一个例子会很棒!
Please note, I know I can use:
请注意,我知道我可以使用:
$('#divToRemove').remove();
however I'd like to be able to use selectors in this instance (reasons outside of scope of question).
但是我希望能够在这种情况下使用选择器(问题范围之外的原因)。
Thanks, Norm.
谢谢,诺姆。
回答by qwertymk
This should be the fastest and safest:
这应该是最快和最安全的:
$('#parent').find('div').first().remove();
回答by user122211
You want
你要
$('#parent').find('div:first').remove();
or it will remove all <div>
within the parent <div>
.
否则它将删除所有<div>
父级中的内容<div>
。
回答by Elliot Yap
let's say. you are doing JS event and you have access to "this" I will do it this way.
让我们说。你正在做 JS 事件并且你可以访问“这个”我会这样做。
$('#child').click(function(){
$(this).closest('div#parent').children('div:first').remove();
});
clarify, this is not the most efficient way but useful in interactive event. alternatively, you can make use of a few selector :
澄清一下,这不是最有效的方式,但在交互式事件中很有用。或者,您可以使用一些选择器:
//closest,parent,next,prev,find,children and nth-child()
回答by Jasper
Ive got another one:
我还有一个:
$('#parent > div:first').remove();
The '>' selects children of the element referenced to the left, and of course ':first" refers to the first child.
'>' 选择引用到左边的元素的子元素,当然 ':first" 指的是第一个子元素。
回答by faizalSalleh
you can try this. It work perfectly on me
你可以试试这个。它对我来说完美无缺
$('#parent').find('div:first').remove();
$('#parent').find('div:first').remove();
回答by Calvin
$('#parent').children('div:first').remove();
use this if you're only talking about removing immediate children div of parent. and it will be better than .find() when you have more inner divs.
如果您只是在谈论删除父级的直接子级 div,请使用此选项。当你有更多的内部 div 时,它会比 .find() 更好。