gpt4 book ai didi

javascript - 为什么 "appendChild"移动一个节点?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:17:11 26 4
gpt4 key购买 nike

我在玩原生 javascript。我基本上是在练习基本的节点操作,例如添加、删除、移动、复制和创建。

在测试 move 时,我遇到了一个问题。

http://jsfiddle.net/sJg7E/

如果您查看上面的 jsfiddle,我使用了“appendChild”。它如何将节点移动到新的 div?我知道如果我想复制一个节点,我需要克隆一个节点。它只是看起来/听起来不适合“appendChild”命令。

这是预期的行为吗?

最佳答案

一个节点只能有一个父节点。因此,如果您将它附加到另一个节点,它会移动它。

来自 documentation of appendChild :

Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

来自同一页面:

You can use cloneNode to make a copy of the node before appending it under the new parent. (Note that the copies made with cloneNode will not be automatically kept in sync.)

另请注意:

This method is not allowed to move nodes between different documents. If you want to append node from a different document (for example to display results from AJAX request) you must first use importNode.

您还可以阅读 appendChild 的 w3c 规范:

Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.

关于javascript - 为什么 "appendChild"移动一个节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146888/

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