这是一个关于 javascript 如何编译(我认为)以及文本如何附加到 HTML 文档的问题。
我正在关注一个例子 here因为我想以交互方式将元素附加到文档中的列表。
我的 html 文件包含一个列表:
<ul id="sList">
</ul>
如果我这样写javascript:
var textnode = document.createTextNode(s);
var node = document.createElement("li");
node.appendChild(textnode);
document.getElementById("sList").appendChild(node);
每个字符串(每个字符串都保存在变量 s 中)被附加到文档中的列表中。
我天真地以为我可以用更少的行数来写这个。
var node = document.createElement("li");
node.appendChild(document.createTextNode(s));
document.getElementById("sList").appendChild(node);
按预期工作,将每个 s 作为列表项附加到列表中,但如果我尝试通过不将创建的“li”存储为变量来进一步减少代码,则每个都无法正确显示为列表项。例如,此脚本在标签之间附加文本但不作为列表项:
var textnode = document.createTextNode(s)
var node = (document.createElement("li")).appendChild(textnode)
document.getElementById("sList").appendChild(node)
同样,我的第一次尝试是单行代码:
document.getElementById("sList").appendChild(document.createElement("li").appendChild(document.createTextNode(s)))
它还在 <ul>
中追加文本标签,但不作为列表项。
所以我只是想知道编译器如何解释文本节点对尚未创建的 document.createElement 的 appendChild 调用,以及是否可以将项目附加到列表而不先将它们存储为变量。这个问题是出于好奇,但我想更好地理解 DOM 以及如何用更少的 javascript 做更多的事情也会很好。
最佳答案
So I am just wondering how the compiler interprets an appendChild call of a text node to a document.createElement that hasn't been created yet...
这不是编译器,而是 DOM。并且元素已经被创建(你调用了createElement
);还没有发生的是您还没有将它添加到文档中,但没关系,它仍然是一个对象,它仍然可以附加其他对象。
and whether it's possible to append items to a list without storing them as variables first.
是的,通过使用 appendChild
的返回值,is the child element that was appended :
list.appendChild(document.createElement('li')).appendChild(document.createTextNode(s));
所以我们:
- 创建
li
元素 - 将其添加到列表中
- 使用追加的返回值(
li
元素)追加文本节点
For example, this appends text between tags but not as list items:
var textnode = document.createTextNode(s) var node = (document.createElement("li")).appendChild(textnode) document.getElementById("sList").appendChild(node)
那是因为您将 appendChild
的返回值附加到列表中。 appendChild
的返回值是附加的子元素,不是它附加到的元素。所以node
指的是文本节点。将该节点附加到 li
后,您可以将其移动到上面最后一行的 list
。
关于javascript - 如何将文本作为列表项以交互方式附加到 HTML 文档中的列表而不将列表项存储为 javascript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33018564/