【问题标题】:I'm trying to add some rows to an HTML table, but it's failing我正在尝试向 HTML 表中添加一些行,但它失败了
【发布时间】:2011-08-25 14:17:20
【问题描述】:

注意:这是一个社区 wiki 帖子

以下代码使用简单的 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>

【问题讨论】:

标签: javascript html dom html-table


【解决方案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);

【讨论】:

    【解决方案2】:

    这里的问题是&lt;table&gt; 元素的正确结构不存在。处理表格时,基本结构是:

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

    逻辑是,在处理表格时,您希望将列的标签与实际数据分开。因为大多数浏览器填写&lt;tbody&gt;作为修复损坏的HTML过程的一部分,很少有人意识到这一点。当浏览器看到你添加了&lt;tr&gt;时,它不知道你是在尝试将它添加到&lt;thead&gt;还是&lt;tbody&gt;,所以它失败了。

    以下显示了添加行的正确方法:

    <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 被指控有罪。坦率地说,我几乎从不打扰表格中的 thead 和 tbody 标签。现在我会的。 :-)
    • 需要指出的是tbodythead实际上只在严格的XHTML中是必需的,而且基本上每个浏览器都支持insertCell and insertRow
    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2021-04-09
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2011-06-21
    • 1970-01-01
    相关资源
    最近更新 更多