2012-03-13 89 views
0

这里是我的代码...“不能调用方法‘的appendChild’为空” ......错误...为什么?

var main = document.getElementById("section"); //gets node for main window 
     var para1 = document.createElement("p");  //creates paragraph  node 
     var para2 = document.createElement("p"); // creates another paragraph node 

     var req = request.responseXML; //gets xml data 

     var nodeList = req.getElementsByTagName("line"); //gets all nodes with line as tag 
     var nodeArray = new Array(); //holds only lines that are part of code 

     para1.appendChild(document.createTextNode(req.getElementsByTagName("description")[0].childNodes[0].nodeValue)); //creates text node to put inside paragraph node 
     para2.appendChild(document.createElement("table")); //creates a table tag and puts inside para2 

     for(var i=0; i<nodeList.length; i++) 
     { 
      if(nodeList[i].getAttribute("st") == "no") 
      { 
       document.getElementById("table").appendChild(document.createElement("tr")); //creates a table row for each line participating in quiz 
       //document.getElementById("tr").appendChild(document.createElement("td")); //creates table data for the row (only one)dd 
       //nodeArray.push(nodeList[i].childNodes[0].nodeValue); //adds to array the lines participating in quiz   
       //document.getElementById("td").appendChild(createTextNode(nodeList[i],childNodes[0].nodeValue)); 
      } 
     } 


     main.appendChild(para1); //add paragraph to the main div 
     main.appendChild(para2); //adds 2nd paragraph to main div 
    } 

所以我在if语句注释掉一切了,但我仍然收到此错误......如果我已经创建的表标签更早,为什么认为是空的?

+0

不要追加TR元素表元素IE <9将抛出一个错误,你必须将它们添加到TBODY元素。其他的browers将插入TBODY你,如果它的丢失或自动添加行到最后一个tbody元素,但不是IE浏览器。 – RobG 2012-03-13 03:23:17

回答

3

你的代码更改为:

var table = para2.appendChild(document.createElement("table")); 
var tbody = table.appendChild(document.createElement('tbody')); 

现在行添加到tbody。其他答案告诉你关于getElementById的错误。对你的问题的评论告诉你为什么要创建一个TBODY元素。

+0

是的,它做到了!非常感谢 – carinlynchin 2012-03-13 03:34:42

0

您没有分配“表”的ID表,这样你就不会通过的getElementById(“表”)中找到它。

要么分配相应的ID表或使用的getElementsByTagName。

+0

我改成了这一点,但随后得到这个错误:遗漏的类型错误:对象#没有法“的appendChild” – carinlynchin 2012-03-13 03:23:51

+0

的getElementsByTagName会返回一个节点列表,不喜欢的getElementById单个元素一样。您可以在元素上使用appendChild,但不能使用NodeList。 – Steve 2012-03-13 03:36:02

0
para2.appendChild(document.createElement("table")); 

这通过使用getElementsByName

0

创建名称为“表”,而不是ID“表”

在你的if块,访问的一个元素你必须多次打电话给appendChild,所以现在还很难验证错误发生在“表格”行上。话虽如此,你打电话document.getElementById,不document.getElementsByTagName这意味着你需要用一个id table创建表:

<table id="table"> 
... 
</table> 
相关问题