gpt4 book ai didi

javascript - Node.cloneNode() 与 DOM 规范不一致

转载 作者:可可西里 更新时间:2023-11-01 14:47:32 29 4
gpt4 key购买 nike

使用 Node.cloneNode(true) 有据可查(主要在 SO 上)在 <input type="text"> 上返回一个新的 <input>与原始节点具有相同文本内容的节点,但克隆了一个 <select> (在用户选择之后)返回一个新的 <select>无需用户选择。这起初似乎不符合规范,因为根据 DOM 3 :

cloneNode
Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes. The duplicate node has no parent (parentNode is null) and no user data. User data associated to the imported node is not carried over.

为什么会发生这种情况的答案稍后会详细说明,但在 DOM 2 spec 中更清楚,

cloneNode
Cloning an Element copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes, but this method does not copy any text it contains unless it is a deep clone, since the text is contained in a child Text node.

鉴于这种措辞,我愿意接受这种行为,尽管我认为 <input>不包含文本节点,因为 childNodes <input> 的属性永远是空的 NodeList不管它是否包含文本(在规范的措辞中,“有一个文本节点”)。

至少,我明白了<option>用户选择被视为用户数据,因此不克隆是有道理的。在这种情况下,此“用户数据”包含在 selected<option> 的属性(property).

然而,当trying the behavior with radio buttons and checkboxes ,Chrome 38、FF 33、Safari 6.2 中的行为,完全违背了上述定义。克隆选中的复选框或选中的单选按钮会保持其选中状态。这似乎与规范相反,因为此信息是“用户数据”,它(如 <select> )包含在属性中(在本例中为 checked )。

我是否正确认为这不符合规范?如果没有,是否有其他地方定义了这种行为?如果是,是否有一个用例可以解释为什么 cloneNode()它如何克隆用户输入字段的状态如此不一致?


编辑: 在针对我的浏览器套件进行测试时,我发现 Opera 12.15 的性能与 <select> 的预期一样。输入。即,它保留了克隆时的用户选择。

最佳答案

DOM Level 4 定义 cloning steps更清楚:

Specifications may define cloning steps for all or some nodes. The algorithm is passed copy, node, document, and optionally a clone children flag, as indicated in the clone algorithm.

To clone a node, optionally with a document and a clone children flag, run these steps:

  1. If document is not given, let document be node's node document.

  2. Let copy be a node that implements the same interfaces as node.

  3. If copy is a document, set its node document and document to copy.
    Otherwise, set copy's node document to document.

  4. Copy the following from node to copy, depending on the type of node:

  5. Run any cloning steps defined for node in other applicable specifications and pass copy, node, document and the clone children flag if set, as parameters.

  6. If the clone children flag is set, clone all the children of node and append them to copy, with document as specified and the clone children flag being set.

  7. Return copy.

The cloneNode(deep) method must return a clone of the context object, with the clone children flag set if deep is true.

selectinput 都是Element,所以只有它们的namespace , namespace prefix , local name , 及其 attribute list应在步骤 4 中复制。

但是,在第 5 步中,可能会运行额外的克隆步骤。在 input 元素的情况下,这些步骤可能包括复制 valueselected 属性。

关于javascript - Node.cloneNode() 与 DOM 规范不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27193301/

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