我最近编写了一个脚本,其中需要一个元素在单击时移动到顶部。我在 onclick 函数中使用了以下代码,并且已经使用多年了:
this.parentNode.appendChild(this.parentNode.removeChild(this));
该脚本无法正常工作,因此我对代码进行了修改,尝试了以前从未做过的事情来修复它。我认为问题可能出在这行代码上。实际上,事实证明它与它无关,但是当我修补时,我注意到以下代码似乎执行相同的功能。
this.parentNode.appendChild(this);
据我所知,没有什么区别。前者对我来说感觉“更好”,但我不能真正说出原因。有实际区别吗?如果没有,我将开始使用后者并节省十八个字符:-)
最佳答案
this
不是 this
的子项。
您需要从父节点中删除子节点。
但是,appendChild
将 implicitly remove the node from any existing parent (元素不能有多个父元素):
If the node already exists it is removed from current parent node, then added to new parent node.
关于javascript - onclick 删除并重新插入 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147293/