2012-12-17 38 views
5

我开始使用JavaScript和DOM,试图故意远离jQuery等等,至少在一段时间内。考虑到这一点,教程通常提供了一个例子,如本:了解基本的DOM链接

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元素的最后,获得一个append而不是前置。

我想成功的第一个案例只是一个侥幸,但我不明白这个链式练习有什么问题。

+1

您关闭'的insertBefore( )'createElement()'之后的'parens'。所以这个链似乎继续使用'appendChild()'方法。这令我感到惊讶,我会预料到一个错误。 –

+1

尽管像这样链接作为了解这些方法如何工作的方法很有趣,但结果更难以阅读。必须向右滚动才能看到整个语句是令人讨厌的,但是您可以在'.appendChild()'之前或者在打开一个或多个方法的后面放置一个换行符... – nnnnnn

+1

使用缩小工具“避免变量“ - 你只是让你的代码难以阅读,维护和扩展。 – jbabey

回答

6

你在错误的地方有括号。您行:

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) 

伙计们,请不要使用这样的代码,这仅仅是用于教育目的)))

+0

请注意,'.appendChild()'返回_child_元素,因此只需切换括号即可解决问题。 – nnnnnn

+0

这不是一个“问题”))我刚刚向括号中显示了他的错误。所有其他代码在这里是“避免变量”,这是毫无意义的至少 – SergeyS

+0

看到更新的答案,以满足所有OP“要求” – SergeyS