gpt4 book ai didi

javascript - removeChild 是递归的吗?

转载 作者:行者123 更新时间:2023-11-30 18:38:26 26 4
gpt4 key购买 nike

我使用 document.createElement 创建了许多新的页面元素(在一些任意层次结构中),并且一直在使用 element.removeChild() 删除我不再需要的元素。我想知道这是否也能正确清理所有子元素,或者我是否应该使用某种递归函数。 Javascript 使用垃圾收集器,所以我不需要担心这个,对吧?

最佳答案

使用element.removeChild(childElement)从文档树中删除节点。但是,如果您有对该元素的引用,则该元素不会被垃圾收集 (GC)。

考虑:
示例 1(可怕的做法):

<body><script>
var d = document.createElement("div");
document.body.appendChild(d);
document.body.removeChild(d);
//The global scope won't disappear. Therefore, the variable d will stay,
// which is a reference to DIV --> The DIV element won't be GC-ed
</script></body>

示例 2(不良做法):

function foo(){
var s = document.createElement("span");
document.body.appendChild(s);
s.innerHTML = "This could be a huge tree.";
document.body.addEventListener("click", function(ev){
alert(eval(prompt("s will still refer to the element:", "s")));
//Use the provided eval to see that s and s.innerHTML still exist
// Because this event listener is added in the same scope as where
// DIV `d` is created.
}, true);
document.body.removeChild(s);
}
foo();

示例 3(良好实践):

function main(){
//Functions defined below
addDOM();
addEvent();
remove();
//Zero variables have been leaked to this scope.

function addDOM(){
var d = document.createElement("div");
d.id = "doc-rob";
document.body.appendChild(d);
}
function addEvent(){
var e = document.getElementById("doc-rob");
document.body.addEventListener("click", function(ev){
e && alert(e.tagName);
//Displays alert("DIV") if the element exists, else: nothing happens.
});
}
function remove(){
var f = document.getElementById("doc-rob");
f.parentNode.removeChild(f);
alert(f);//f is still defined in this scope
Function("alert('Typeof f = ' + typeof f);")(); //alert("Typeof f = undefined")
}
}
main();

关于javascript - removeChild 是递归的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7547634/

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