我已经创建了一个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:
调用“child” div上的“remove”方法
调用“parent1”节点上的“removeChild”方法
但无论哪种情况,该节点实际上都没有被删除。我总是可以将“child” div插入到“parent2”中。
我理解在第二种情况下,“child”已解除与“parent1”的绑定,但实际上没有被删除。但在第一种情况下,“child”不是永久删除了吗?
当尝试插入不存在的元素时,我不应该收到错误吗?
请解释。
如果在调用元素上的“remove”后该元素仍存在:
'remove'与'removeChild'有何不同?就我所看到的,这两种方法都只是将子项从父项中解绑,但元素仍占用内存。
是否有任何方法确保元素实际上已从内存中删除?