首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript中插入一行HTML表体

如何在JavaScript中插入一行HTML表体
EN

Stack Overflow用户
提问于 2013-08-20 19:05:44
回答 11查看 436.5K关注 0票数 168

我有一个带有页眉和页脚的HTML表:

<table id="myTable">
    <thead>
        <tr>
            <th>My Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>aaaaa</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>My footer</td>
        </tr>
    <tfoot>
</table>

我正在尝试使用以下内容在tbody中添加一行:

myTable.insertRow(myTable.rows.length - 1);

但是该行被添加到tfoot部分。

如何插入tbody

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2013-08-20 19:20:16

如果要向tbody中添加一行,请获取对该行的引用并调用其insertRow方法。

var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

// Insert a row at the end of table
var newRow = tbodyRef.insertRow();

// Insert a cell at the end of the row
var newCell = newRow.insertCell();

// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>initial row</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My Footer</td>
    </tr>
  </tfoot>
</table>

(JSFiddle上的旧demo )

票数 269
EN

Stack Overflow用户

发布于 2013-08-20 19:13:21

您可以使用jQuery尝试以下代码片段

$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
票数 45
EN

Stack Overflow用户

发布于 2017-12-09 04:02:19

基本方法:

这将添加HTML格式的内容并显示新添加的行。

var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18333427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档