2012-03-13 87 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> 
相關問題