开发者

Where do .detach-ed objects go?

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.


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:

<div id="a">
  <div id="b">
    <div id="c">
        <div id="d"></div>
    </div>
  </div>
</div>

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 = $('#c')

$('#b').detach()

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.

var b = $('#b').detach()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜