onclick 删除并重新插入 DOM 元素

发布于 2024-11-10 11:02:23 字数 397 浏览 2 评论 0原文

我最近编写了一个脚本,其中需要一个元素在单击时移动到顶部。我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光病人 2024-11-17 11:02:23

this 不是 this 的子项。
您需要从父节点中删除子节点。

但是,appendChild隐式从任何现有父节点中删除节点(元素不能有多个父节点):

如果该节点已存在,则会从当前父节点中删除该节点,然后将其添加到新的父节点中。

this is not a child of this.
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):

If the node already exists it is removed from current parent node, then added to new parent node.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文