2016-07-07 82 views
0

我可以知道如何將項目插入到我的表體中?我的代碼似乎不工作。將行添加到現有表

var tableRef = document.getElementById("myList").getElementsByTagName("tbody"); 

var newRow = tableRef.insertRow(tableRef.rows.length); 

var newCell = tableRef.insertCell(0); 

var myTextTwo = "hello world"; 

var newText = document.createTextNode(myTextTwo); 

newCell.appendChild(newText); 
<table id="myList"> 
    <thead> 
    <tr> 
     <td>Product ID</td> 
     <td>Product Name</td> 
     <td>Quantity</td> 
    </tr> 
    </thead> 
    <tbody> 

    </tbody> 
</table> 
+1

你檢查你的JavaScript控制檯中的錯誤? – Blazemonger

+0

@所以你已經從'.getElementsByTagName()'中省略了'[0]',並且你也嘗試添加新的單元到tbody中,而不是你必須添加的新行。看看我的答案更詳細的解釋:http://stackoverflow.com/a/38248819/6313073 –

回答

2

getElementsByTagName返回一個數組。你需要附加[0]來選擇數組中的第一個元素。

您也嘗試使用上tableRefinsertCell,當你要使用它newRow

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0]; 
 

 
var newRow = tableRef.insertRow(tableRef.rows.length); 
 

 
var newCell = newRow.insertCell(0); 
 

 
var myTextTwo = "hello world"; 
 

 
var newText = document.createTextNode(myTextTwo); 
 

 
newCell.appendChild(newText);
<table id="myList"> 
 
    <thead> 
 
    <tr> 
 
     <td>Product ID</td> 
 
     <td>Product Name</td> 
 
     <td>Quantity</td> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 

 
    </tbody> 
 
</table>

+0

如果我想要做一個for循環來遍歷表中的第一列元素,該怎麼辦? @Turnip – Alvin

+0

這聽起來像是一個完全不同的問題。如果您的初始問題已解決,您應該打開一個新標記並將其標記爲已回答。 – Turnip

+1

好的,謝謝隊友! @蕪菁 – Alvin

0

要使其工作,你需要:

1)[0].getElementsByTagName()像下面後,因爲該方法返回元素的數組,不像.getElementById(),它返回一審:

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0]; 

2)使用.insertCell()你想要的單元格是行,在我們的例子中newRow,上不了檯面的tbody

var newCell = newRow.insertCell(0); 

你正確的JavaScript代碼應該是

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0]; 
var newRow = tableRef.insertRow(tableRef.rows.length); 
var newCell = newRow.insertCell(0); 
var myTextTwo = "hello world"; 
var newText = document.createTextNode(myTextTwo); 
newCell.appendChild(newText); 

您還可以看看以下代碼片段

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0]; 
 
var newRow = tableRef.insertRow(tableRef.rows.length); 
 
var newCell = newRow.insertCell(0); 
 
var myTextTwo = "hello world"; 
 
var newText = document.createTextNode(myTextTwo); 
 
newCell.appendChild(newText);
#myList { 
 
    border: 1px solid black; 
 
} 
 
#empty { 
 
    border-bottom: 1px solid black; 
 
}
<table id = "myList"> 
 
    <thead> 
 
    <tr> 
 
     <td>Product ID</td> 
 
     <td>Product Name</td> 
 
     <td>Quantity</td> 
 
    </tr> 
 

 
    <!--- This row is for adding a border-bottom line --> 
 
    <tr> 
 
     <td id = "empty" colspan ="3"></td> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    
 
    </tbody> 
 
</table>

+0

好吧,也會試試這個,謝謝隊友! – Alvin