我开始使用 JavaScript 和 DOM,试图有意识地远离 jQuery 等,至少暂时如此。考虑到这一点,教程通常会提供如下示例:
h = document.createElement("h1");
t = document.createTextNode("Hello.");
h.appendChild(t);
document.body.appendChild(h);
为了简化这一点并避免变量,我成功地链接了以下内容:
document.body.appendChild(document.createElement("h1")).appendChild(document.createTextNode("Hello."));
虽然这可行,但我尝试缩短以下前置操作:
h = document.createElement("h1");
t = document.createTextNode("Put this on top.");
h.appendChild(t);
document.body.insertBefore(h,document.body.firstChild);
具有以下内容:
document.body.insertBefore(document.createElement("h1")).appendChild(document.createTextNode("Put this on top."),document.body.firstChild);
但是这一次它没有按预期工作:文本被放置在 BODY 元素的最末尾,获得了附加而不是前置。
我想第一个成功的案例只是侥幸,但我看不出这种链式做法有什么问题。
最佳答案
你在错误的地方有括号。你的线路:
document.body.insertBefore( document.createElement("h1") )
.appendChild( document.createTextNode("Put this on top."), document.body.firstChild );
它应该如何:
document.body.insertBefore(
document.createElement("h1").appendChild(
document.createTextNode("Put this on top.")), document.body.firstChild);
现在您明白为什么将所有内容合并到一行通常不是一个好主意。
好的,此固定行不会为您提供代码“带变量”的确切行为。这是因为 .appendChild 返回子 DOM 元素(在您的情况下为 <INPUT>
),而不是父元素(在您的情况下为 <H1>
)。但是你想要所有<H1>
在文档的开头添加了 DOM 元素。要在一行中实现这一点,您需要使用 .parentNode 属性:
document.body.insertBefore(
document.createElement("h1").appendChild(
document.createTextNode("Put this on top.")).parentNode, document.body.firstChild)
伙计们,请不要使用这样的代码,这只是为了教育目的)))
关于javascript - 了解基本的 DOM 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13921864/