在jQuery中永久删除元素

时间:2011-05-10 21:39:29

标签: jquery

当我追加一个元素然后删除它时,该对象仍然存在?

bg = $('<div class="dialog_bg"></div>');
$('#'+elm).append(bg);

bg.remove();
那是怎么回事?是不是可以永久删除元素?

3 个答案:

答案 0 :(得分:2)

remove方法只是将对象从DOM中取出,换句话说,将其从页面中取出。你问的是从内存中删除对象吗?在这种情况下,我认为你不能明确地做到这一点 - 为什么你需要? Javascript是garbage collected language

编辑:有关详情,请参阅this question

答案 1 :(得分:2)

所以元素完全从DOM中删除。没关系。您的问题是如何确保元素真正被删除。

我会使用.parent()方法。因为如果元素从DOM中删除,它将不再具有父元素。这可能比$("html").has(bg)更快,因为它不必遍历整个DOM树。

bg = $('<div class="dialog_bg"></div>');
$('#'+elm).append(bg);

bg.remove();

if(bg.parent().length == 0) {
   // removed succesfully
} else {
   // still somewhere in the dom
}

// tells the garbage collector to free the memory because there's no way to access the element anymore
bg = null;

答案 2 :(得分:-1)

怎么样:

$('div.dialog_bg').remove();

你可能在div中添加了一些东西,所以它不再识别它了。