.detached 对象去了哪里?
我有这样的东西:
//html
<div class="panel">
<div class="tools">
<a href="#action1">Action 1</a>
<a href="#action1">Action 1</a>
<a href="#action1">Action 1</a>
</div>
<div class="list">
<table>...</table>
</div>
</div>
//JavaScript (jQuery)
var lookup = $('.panel'),
buttons = lookup.find('.tools').detach().find('a');
...
//append buttons somewhere
所以,这里我将 '.tools'
与 '.panel'
分离,然后我将按钮附加到其他地方。但是 '.tools'
节点呢?它是否被垃圾收集?我是否必须保存独立的 '.tools'
,从中获取按钮然后销毁它?
如果它的问题 - html 部分是通过 AJAX 请求接收的,并且所有这些代码都在 success
处理程序中。
I have something like this:
//html
<div class="panel">
<div class="tools">
<a href="#action1">Action 1</a>
<a href="#action1">Action 1</a>
<a href="#action1">Action 1</a>
</div>
<div class="list">
<table>...</table>
</div>
</div>
//JavaScript (jQuery)
var lookup = $('.panel'),
buttons = lookup.find('.tools').detach().find('a');
...
//append buttons somewhere
So, here i have '.tools'
detached from '.panel'
and then i took buttons and append them somewhere else. But what about '.tools'
node? Does it beeing garbage-collected or not? Do I have to save detached '.tools'
, take buttons from it and than destroy it?
If its matter - html part is received via AJAX request and all this code is inside success
handler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,buttons 变量创建对分离元素的子元素的引用,并且将阻止该元素被垃圾收集,至少在buttons 超出范围之前是如此。
编辑:
为了让某些东西被垃圾收集,它需要从 DOM 中分离出来,并且不能有 JavaScript 变量引用该元素(或分离的节点树中的任何元素),
例如:
如果您想分离“#b”并对其进行垃圾回收,则不能有任何变量指向元素 b、c 或 d。
这是行不通的:
var c 将保留对元素 #c 的引用,该元素是 #b 的一部分,因此不能被垃圾收集。
这也不起作用,因为分离返回对要分离的元素的引用。
In this case, the buttons variable creates a reference to a child of the detached element, and will prevent the element from getting garbage collected, at least until buttons goes out of scope.
EDIT:
In order for something to be garbage collected, it needs to be detached from the DOM, and there must be no JavaScript variables referencing the element (or any elements within the detached node tree)
For example:
If you want to detach "#b" and have it garbage collected, you can't have any variables pointing to elements b, c, or d.
This would not work:
var c would keep a reference to element #c which is part of #b, so be can not be garbage collected.
This does not work either, because detach returns a reference to the element you are detaching.