2016-04-16 34 views
1

我遇到了一些我认为在JavaScript中很奇怪的东西。我正在构建一种形式,其思想是提供按需添加表格行和字段的能力。您可以想象我开始尝试使用createElement,appendChild等。JavaScript通过检索并传递输入信息nodeValue vs createTextNode

为什么当我尝试从输入字段传递一个值时,它不能直接附加并输出到div标记?但是,当通过createTextNode首先将检索到的值传递并输出时,它将起作用。

控制台说,级联pat.appendChild(人)是不是一个 对象

pat.appendChild(text)正常工作?

<script type="text/javascript"> 

function appendTr(){ 

    var pat = document.createElement("p"); 
    /*var formValue = document.createTextNode("This works, but why doesn\'t the other one"); 
    p.appendChild(formValue);*/ 
    var al = document.getElementById("position").value; 
    var text = document.createTextNode(al); 
    pat.appendChild(text); 
    document.getElementById("outer").appendChild(pat); 
} 

</script> 
<form> 
    <table id="job"> 
     <tr> 
      <td><input id="y1" name="y1" type="text"></td> 
      <td><input id="y2" name="y2" type="text"></td> 
      <td><input id="position" name="position" type="text"></td> 
      <td><input id="org" name="org" type="text"></td> 
      <td><input class="button" id="addRow" type="button" value="+" onclick="appendTr()"></td> 
      </tr> 
    </table> 

</form> 
<div id="outer">Not</div> 
+0

你能提供的jsfiddle证明问题,告诉我们您使用的浏览器是什么?我无法复制你描述的'pat.appendChild(al)不是对象'的错误。 – Mahout

回答

0

al是一个字符串和text是一个节点。 appendChild的参数必须是节点。

要输出al直接进入一个div做这样的事情:

document.getElementById("outer").textContent=al; 

,或者您希望在al HTML代码的工作:

document.getElementById("outer").innerHTML=al;