jQuery 从父节点中删除所有子节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3044780/
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
Remove all child nodes from a parent?
提问by user246114
I have a list, I just want to remove all child nodes from it. What's the most efficient way using jquery? This is what I have:
我有一个列表,我只想从中删除所有子节点。使用 jquery 最有效的方法是什么?这就是我所拥有的:
<ul id='foo'>
<li>a</li>
<li>b</li>
</ul>
var thelist = document.getElementById("foo");
while (thelist.hasChildNodes()){
thelist.removeChild(thelist.lastChild);
}
is there a shortcut rather than removing each item, one at a time?
是否有快捷方式而不是一次删除每个项目?
----------- Edit ----------------
- - - - - - 编辑 - - - - - - - -
Each list element has some data attached to it, and a click handler like this:
每个列表元素都有一些附加的数据,以及一个像这样的点击处理程序:
$('#foo').delegate('li', 'click', function() {
alert('hi!');
});
// adds element to the list at runtime
function addListElement() {
var element = $('<li>hi</hi>');
element.data('grade', new Grade());
}
eventually I might add buttons per list item too - so it looks like empty() is the way to go, to make sure there are no memory leaks?
最终我也可能为每个列表项添加按钮 - 所以看起来 empty() 是要走的路,以确保没有内存泄漏?
回答by Nick Craver
回答by Marco Ottina
A other users suggested,
其他用户建议,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
足够好,因为它删除了所有后代节点(标签节点和文本节点)以及存储在这些节点内的所有类型的数据。请参阅JQuery 的 API 空文档。
If you wish to keep data, like event handlers for example, you should use
如果您希望保留数据,例如事件处理程序,您应该使用
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
方法 .remove() 可用于类似目的。