onclick 删除并重新插入 DOM 元素
我最近编写了一个脚本,其中需要一个元素在单击时移动到顶部。我在 onclick 函数中使用并且多年来一直使用以下代码:
this.parentNode.appendChild(this.parentNode.removeChild(this));
该脚本无法正常工作,因此我对代码进行了修改,尝试了以前从未做过的事情来修复它。我认为问题可能出在这行代码上。实际上,事实证明它与它无关,但是当我修补时,我注意到下面的代码似乎执行相同的功能。
this.parentNode.appendChild(this);
据我所知,没有什么区别。前者对我来说感觉“更好”,但我不能真正说出原因。有实际区别吗?如果没有,我将开始使用后者并节省十八个字符:-)
I recently wrote a script in which I needed an element to move to the top when it was clicked on. I used, and have been using for years, the following code in the onclick function:
this.parentNode.appendChild(this.parentNode.removeChild(this));
The script wasn't working, and so I messed around with the code, trying things I'd never done before in an effort to fix it. I thought the problem might lie in this line of code. Actually, it turned out to have nothing to do with it, but while I was tinkering around, I noticed that the following code seems to perform the same function.
this.parentNode.appendChild(this);
As far as I can tell, there is no difference. The former feels "better" to me, but I can't really say why. Is there an actual difference? If not, I'll start using the latter and save eighteen characters :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this
不是this
的子项。您需要从父节点中删除子节点。
但是,
appendChild
将隐式从任何现有父节点中删除节点(元素不能有多个父节点):this
is not a child ofthis
.You need to remove the child from the parent node.
However,
appendChild
will implicitly remove the node from any existing parent (elements cannot have multiple parents):