问题:
我试图理解为什么我不能像这样将 appendChild()
方法链接到 document.createElement()
:
var listItem = document.createElement('li').appendChild(text);
HTML
<ul>
<li id="one"><em>fresh</em> figs</li>
<li id="two">pine nuts</li>
<li id="three">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
我知道这是正确的做法:
var ul = document.getElementsByTagName('ul')[0];
var txt = document.createTextNode('this is a text string');
var el = document.createElement('li');
el.appendChild(txt);
但为什么当我这样做时:
var ul = document.getElementsByTagName('ul')[0];
var text = document.createTextNode('I am the first generated list');
var listItem = document.createElement('li').appendChild(text);
ul.appendChild(listItem);
它删除了我形成的 li 元素,并将文本仅添加到 ul 项目! 为什么?
最佳答案
因为 appendChild
不是为那样工作而设计的。本来可以的,但事实并非如此。要以这种方式工作,appendChild
必须返回对调用它的元素的引用,但它没有;它返回您传递给它的参数。
it deletes the li element I formed
不,它不会删除它;它从不附加它,因为 listItem
不是对您创建的元素的引用;它是文本节点。来自DOM3 spec :
appendChild
(modified in DOM Level 3)Adds the node
newChild
to the end of the list of children of this node. If thenewChild
is already in the tree, it is first removed.Parameters
newChild
of typeNode
The node to add. If it is a DocumentFragment object, the entire contents of the document fragment are moved into the child list of this nodeReturn Value
Node
The node added.
记下返回值。
关于javascript - 为什么 appendChild() 覆盖 createElement() 如果它被链接在它的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977192/