我正在尝试向HTML表添加一些行,但它失败了

时间:2011-05-14 17:04:57

标签: javascript html dom html-table

注意: 这是一个社区维基帖子

使用简单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>

2 个答案:

答案 0 :(得分:9)

这里的问题是<table>元素的正确结构不存在。处理表时,基本结构是:

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

逻辑是,在处理表时,您希望保留列的标签,并将实际数据分开。因为大多数浏览器都会在修复损坏的HTML的过程中填写<tbody>,所以很少有人意识到这一点。当浏览器看到您添加<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>

答案 1 :(得分:-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);
相关问题