我觉得我误会了.removeChild
的工作方式。我在这里有一些代码:
//organization is a string value gotten from an Input node
if (organization == '') {
//there is nothing in the organization form
if (orgContainer !== undefined) {
console.log(orgContainer + ' exists and there is nothing in the organization form.');
//remove the orgContainer
orgContainer.parentNode.removeChild(orgContainer);
console.log(orgContainer + 'removed!');
} else {
console.log(orgContainer + ' does not exist and there is nothing in the organization form.')
}
} else {
if (orgContainer !== undefined || orgContainer !== null) {
console.log(orgContainer + ' exists and there is something in the organization form.');
} else {
console.log(orgContainer + ' does not exist and there is something in the organization form.')
}
}
基本上,当我在调用
orgContainer.parentNode.removeChild(orgContainer)
后检查页面时,再次运行该函数时会收到orgContainer removed!
BUT的控制台日志消息,它说orgContainer
仍然存在,即使我用.removeChild
删除了它?我是否误解了
.removeChild
的工作原理?我的节点已从父节点中删除,但是它实际上不停止存在吗?它是否只是从DOM中删除而不是从内存中删除?我得到了这个美妙的console.log消息
undefined exists and there is something in the organization form.
..什么? undefined
如何存在?我已经阅读了developer.mozilla.org网站上的文档,但仍然有些困惑。任何帮助,将不胜感激,谢谢! 最佳答案
您的JavaScript变量仍然具有对该节点的引用,并且您的代码中没有任何内容尝试更改该引用。您已成功将节点从DOM中取出,但是orgContainer
变量的值从未更改。