removeChild是否真的删除元素? [英] Does removeChild really delete the element?

查看:241
本文介绍了removeChild是否真的删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

removeChild 功能是否完全删除子节点?或者它只是删除指定的parant节点的子元素?如果没有真正删除元素,是否有一种完全删除元素的方法?

Does removeChild function really delete the child node completely? Or it just removes the element being child of the specified parant node? If it doesn't really deletes the element, is there a way to delete the element completely?

推荐答案

removeChild 方法只是将其从其父项中删除。如果它是页面的可见元素,它将从页面中删除。

The removeChild method simply removes it from its parent. If it’s a visible element of the page, it will be removed from the page.

但是Javascript有垃圾回收。这意味着只要任何变量引用它,节点对象本身将保持存在。因此,您可以将一个节点分配给变量,使用 removeChild 从其父节点修剪它,然后将其插入或附加到其他节点,从而有效地在页面上移动它。

But Javascript has garbage collection. This means that the node object itself will remain in existence as long as any variable refers to it. So you can assign a node to a variable, use removeChild to 'prune' it from its parent node, and later on, insert or append it to some other node, thereby effectively moving it around on the page.

以下代码将删除一个节点,并等待10秒钟,然后重新添加到树(因此到页面) :

The following code will remove a node, and wait 10 seconds before re-adding it to the tree (and thus, to the page):

var oldNode = someNode.removeChild(...);
setTimeout(function () {
  document.documentElement.appendChild(oldNode);
}, 10000);

这意味着节点对象尚未从内存中删除,因为还有一个变量指向它(即 oldNode )。

This means that the node object hasn’t been deleted from memory, because there’s still a variable pointing to it (namely, oldNode).

另一种情况:

var node = document.getElementById('test');
// ... do stuff
node.parentElement.removeChild(node);
// 'node' still exists, but has been removed from the page
// ... do some more stuff
node = document.getElementById('hello');
// The variable 'node' now points to something else; 
//  this means the original node will be deleted from memory

如果在其他手,你不要将删除的节点重新分配给另一个变量,它不能被访问(不是通过文档树,因为它已经从那里删除;而不是通过JS变量);所以Javascript会自动从内存中清除它:

If, on the other hand, you don’t reassign the removed node to another variable, it can’t be accessed anymore (not via the document tree, since it’s been removed from there; and not via a JS variable); so Javascript will automatically purge it from memory:

someNode.removeChild(...);

将删除的节点分配给变量,然后分配 null

Assigning the removed node to a variable, and then assigning null (or anything else) to that variable — like Marc B suggests in his answer — is completely unnecessary and, IMHO, silly.

这篇关于removeChild是否真的删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆