【发布时间】:2016-05-03 08:10:15
【问题描述】:
我创建了一个 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>
这里我尝试通过两种方式删除“子”div:
-
通过调用 'child' div 上的 'remove' 方法
-
通过调用“parent1”节点上的“removeChild”方法
但是在这两种情况下,节点实际上并没有被删除。我总是可以将 'child' div 插入到 'parent2'。
我可以理解,在第二种情况下,'child' 与'parent1' 未绑定,实际上并未被删除。但在第一种情况下,“孩子”是否不会被永久删除?
我在尝试插入不存在的元素时不应该得到错误吗?
请解释一下。
如果在元素上调用“删除”后元素确实存在:
-
“remove”与“removeChild”有何不同?如我所见,这两种方法都只是从父级中解绑子级,但元素仍然占用内存。
-
有什么方法可以确保元素实际上从内存中删除?
【问题讨论】:
标签: javascript html