2011-05-14 35 views
3

注:這意味着是一個社區維基職位我想一些行添加到HTML表,但它的失敗

使用簡單的DOM方法下面的代碼無法將行添加到桌子。有什麼問題?

<html> 
<head> 
<title>Javascript Test</title> 
<script> 
function addRow() { 
    var mytable = document.getElementById('mytable'); 

    var row = document.createElement('tr'); 
    var cell = document.createElement('td'); 
    var text = document.createTextNode('This is a row'); 

    cell.appendChild(text); 
    row.appendChild(cell); 
    mytable.appendChild(row); 
} 
</script> 
</head> 
<body> 
<form action="#"> 

<table id="mytable"> 
<tr> 
    <td>This is a row</td> 
</tr> 
</table> 

<input type="button" onclick="addRow()" value="Add A Row"/> 
</form> 
</body> 
</html> 
+0

一個更深入的例子: http://stackoverflow.com/a/19561902/2536357 – tuned 2013-10-24 09:32:03

回答

8

這裏的問題在於<table>元素的正確結構不存在。當表時,其基本結構是:

<table> 
<thead> 
<tr> 
    <th>Heading for the table</th> 
</tr> 
</thead> 
<tbody> 
    <tr> 
    <td>A row of data</td> 
    </tr> 
</tbody> 
</table> 

的邏輯是,與表打交道時,你要保持列的標籤和實際數據分開。由於大多數瀏覽器填寫了<tbody>作爲修復破損HTML過程的一部分,很少有人意識到這一點。當瀏覽器看到你添加一個<tr>時,它不知道你是否試圖將它添加到<thead><tbody>,所以它失敗。

下面顯示了正確的方法,用於將行:

<html> 
<head> 
<title>Javascript Test</title> 
<script> 
function addRow() { 
    var mytbody = document.getElementById('mytbody'); 

    var row = document.createElement('tr'); 
    var cell = document.createElement('td'); 
    var text = document.createTextNode('This is a row'); 

    cell.appendChild(text); 
    row.appendChild(cell); 
    mytbody.appendChild(row); 
} 
</script> 
</head> 
<body> 
<form action="#"> 

<table id="mytable"> 
<tbody id="mytbody"> 
<tr> 
    <td>This is a row</td> 
</tr> 
</tbody> 
</table> 

<input type="button" onclick="addRow()" value="Add A Row"/> 
</form> 
</body> 
</html> 
+0

謝謝你。 – 2011-05-14 17:08:02

+0

+1有罪。我坦率地說幾乎從來不會打擾表中的ad和tbody標籤。現在我會。 :-) – klabranche 2011-05-14 17:18:20

+0

重要的是要指出'tbody'和'thead'實際上只在嚴格的XHTML中是必需的,基本上每個瀏覽器都支持['insertCell'和'insertRow'](http://www.quirksmode.org /dom/w3c_html.html#tables) – sdleihssirhc 2011-05-14 17:23:59

-1

任何額外的行需要被添加,然後取TABLEID的第一個子然後使用appendChild()方法:

var tbl=document.getElementById("tbl"); 
var row=document.createElement("tr"); 
var cel=document.createElement("td"); 
cel.innerHTML='sometext'; 
row.appendChild(cel); 
tbl.children[0].appendChild(row); 
相關問題