Javascript jQuery empty() 与 remove()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3090662/
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
jQuery empty() vs remove()
提问by mabuzer
What's the difference between empty()and remove()methods in jQuery, and when we call any of these methods, the objects being created will be destroyed and memory released?
empty()和 中的remove()方法有什么区别jQuery,当我们调用这些方法中的任何一个时,正在创建的对象将被销毁并释放内存?
回答by nickf
empty()will remove all the contents of the selection.remove()will remove the selection and its contents.
empty()将删除选择的所有内容。remove()将删除选择及其内容。
Consider:
考虑:
<div>
<p><strong>foo</strong></p>
</div>
$('p').empty(); // --> "<div><p></p></div>"
// whereas,
$('p').remove(); // --> "<div></div>"
Both of them remove the DOM objects and should release the memory they take up, yes.
它们都删除了 DOM 对象,并且应该释放它们占用的内存,是的。
回答by Darin Dimitrov
The documentation explains it very well. It also contains examples:
文档很好地解释了它。它还包含示例:
before:
前:
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
.remove():
。消除():
$('.hello').remove();
after:
后:
<div class="container">
<div class="goodbye">Goodbye</div>
</div>
before:
前:
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
.empty():
。空的():
$('.hello').empty();
after:
后:
<div class="container">
<div class="hello"></div>
<div class="goodbye">Goodbye</div>
</div>
As far as memory is concerned, once an element is removed from the DOM and there are no more references to it the garbage collector will reclaim the memory when it runs.
就内存而言,一旦一个元素从 DOM 中移除并且不再有对它的引用,垃圾收集器将在运行时回收内存。
回答by user1452840
$("body").empty()-- it' removes the HTML DOM elements inside the body tag -
$("body").empty()-- 它'删除了 body 标签内的 HTML DOM 元素-
when you declare $("body").remove()- it remove the entire HTML DOM along with body TAG .
当您声明时 $("body").remove()- 它会删除整个 HTML DOM 以及 body TAG 。

