gpt4 book ai didi

javascript - JavaScript 中的 'remove' 和 'removeChild' 方法有什么区别?

转载 作者:搜寻专家 更新时间:2023-11-01 04:48:22 32 4
gpt4 key购买 nike

我创建了一个 HTML 页面来了解如何删除元素。

代码:

<html>
<head>
<script>
var childDiv = null;
var parent1 = null;
var parent2 = null;
function init() {
childDiv = document.getElementById("child");
parent1 = document.getElementById("parent1");
parent2 = document.getElementById("parent2");
}

function rem() {
if (childDiv) {
childDiv.remove();
alert("child removed");
} else {
alert("child does not exist");
}
}

function remChild() {
if (childDiv){
if (parent1.children.length > 0) {
parent1.removeChild(childDiv);
alert("child unbound from parent");
} else {
alert("child exists but is not bound to parent");
}
} else {
alert("child does not exist");

}
}

function ins() {
if (childDiv) {
parent2.appendChild(childDiv);

alert("child inserted to another parent");
}
}
</script>
</head>
<body onload="init()">
<div id="parent1">
<div id="child"></div>
</div>
<div id="parent2"></div>
<button onclick="rem()">remove</button>
<button onclick="remChild()">removeChild</button>
<button onclick="ins()">insert</button>
</body>
</html>

这里我尝试通过两种方式删除'child' div:

  1. 通过调用“child”div 上的“remove”方法

  2. 通过调用“parent1”节点上的“removeChild”方法

但在这两种情况下,节点实际上并没有被移除。我总是可以将“child”div 插入“parent2”。

我可以理解,在第二种情况下,“child”与“parent1”解除绑定(bind)并且实际上并未被删除。但在第一种情况下,“ child ”是否没有被永久移除?

我在尝试插入一个不存在的元素时难道不会出错吗?

请解释。

如果在元素上调用“remove”后元素确实存在:

  1. “remove”与“removeChild”有何不同?如我所见,这两种方法都只是将子项与父项解除绑定(bind),但元素仍然占用内存。

  2. 有什么方法可以确保该元素实际上已从内存中删除?

最佳答案

the node is not actually removed

混淆可能是因为您可能认为删除元素意味着杀死或摧毁它。

enter image description here

但其实removal的概念基本上意味着打破 child 与 parent 之间的关系。这只是一个支队。

enter image description here

Shouldn't I get an error while trying to insert an element which does not exist?

不,因为它仍然存在。

How is remove different from removeChild?

remove 只需要对 child 的引用。 removeChild 需要对父项和子项的引用。结果是一样的。

Is there any way to ensure that element is actually removed from memory?

没有。您只能取消引用它,并希望有一个垃圾收集器检测到该对象未被引用,然后将其删除。

关于javascript - JavaScript 中的 'remove' 和 'removeChild' 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36998877/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com