我创建了一个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>
Run Code Online (Sandbox Code Playgroud)
在这里,我尝试以两种方式删除'child'div:
通过在'child' div上调用'remove'方法
通过在'parent1'节点上调用'removeChild'方法
但在这两种情况下,节点实际上都没有被删除.我总是可以将'child'div插入'parent2'.
我可以理解,在第二种情况下,'child'从'parent1'解除绑定,而不是实际删除.但在第一种情况下,"孩子"是不是永久删除了?
尝试插入不存在的元素时,我不应该收到错误吗?
请解释.
如果元素在元素上调用'remove'之后确实存在:
如何'删除'与'removeChild'不同?正如我所看到的,这两种方法都只是来自父节点的未绑定子节点,但元素仍占用内存.
有没有办法确保元素实际从内存中删除?
remove是一个新功能。这是一个快捷方式,可以更轻松地删除元素而无需查找父节点。不幸的是,它在旧版本的 Internet Explorer 上不可用,因此,除非您不想支持此浏览器,否则您必须使用removeChild或使用polyfill。
子元素保留在内存中的原因是您的代码保留对它的引用。
如果你这样做
childDiv = null;
Run Code Online (Sandbox Code Playgroud)
那么就没有指向它的引用,浏览器可以释放内存。
| 归档时间: |
|
| 查看次数: |
3518 次 |
| 最近记录: |