gpt4 book ai didi

javascript - 与 child 一起最安全、最高效地去除元件

转载 作者:行者123 更新时间:2023-11-27 23:01:07 25 4
gpt4 key购买 nike

假设以下标记:

<div id="outterParent">
<div id="innerParent">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
</div>

就安全性(避免内存泄漏)和性能而言,这样做可以吗:

var outterParent = document.getElementById("outterParent");
var innerParent = document.getElementById("innerParent");

outterParent.removeChild(innerParent);

outterParent = innerParent = null;

...或者最好在删除 #innerParent 之前删除每个 .children 元素,如下所示:

var outterParent = document.getElementById("outterParent");
var innerParent = document.getElementById("innerParent");
var child;

while (innerParent.firstChild){
child = innerParent.firstChild;

innerParent.removeChild(child);
}

outterParent.removeChild(innerParent);

outterParent = innerParent = child = null;

最佳答案

这要看情况。如果您在某处引用了子级,并且不将其删除,则无法对父级进行垃圾收集。

var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.parentNode; // #innerParent -> it can't be garbage collected

那么最好取消子引用,或者删除子引用:

var child = document.querySelector('children');
document.getElementById("innerParent").remove();
child.remove();
child.parentNode; // null -> #innerParent might be garbage collected

关于javascript - 与 child 一起最安全、最高效地去除元件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094382/

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