2011-05-14 85 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); 
相关问题