如何在 JavaScript 中的 HTML 表格正文中插入一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18333427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:21:21  来源:igfitidea点击:

How to insert a row in an HTML table body in JavaScript

javascripthtmlhtml-tableinsertrow

提问by Jér?me Verstrynge

I have an HTML table with a header and a footer:

我有一个带有页眉和页脚的 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>

I am trying to add a row in tbodywith the following:

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

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

but the row is added in the tfootsection.

但该行已添加到该tfoot部分中。

How do I insert tbody?

如何插入tbody

回答by Jonathan Naguin

If you want to add a row into the tbody, get a reference to it and add it there.

如果您想在 中添加一行tbody,请获取对它的引用并将其添加到那里。

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

// Insert a row in the table at the last row
var newRow   = tableRef.insertRow();

// Insert a cell in the row at index 0
var newCell  = newRow.insertCell(0);

// Append a text node to the cell
var newText  = document.createTextNode('New row');
newCell.appendChild(newText);

A working demo is here. Also, you can check the documentation of insertRowhere.

一个工作演示在这里。此外,您可以查看insertRow此处的文档。

回答by Sasidharan

You can try the following snippet using jQuery:

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

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

回答by Kurkula

Basic approach:

基本方法:

This should add HTML-formatted content and show the newly added row.

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

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

var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;

回答by Teemu

You're close. Just add the row to the tbodyinstead of table:

你很接近。只需将行添加到tbody而不是table

myTbody.insertRow();

Just get a reference to tBody(myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.

只需在使用前获得对tBody( myTbody)的引用。请注意,您不需要传递表中的最后一个位置;省略参数时,它会自动定位在末尾。

A live demo is at jsFiddle.

jsFiddle 有一个现场演示

回答by Marwan

I think this script is what exactly you need

我认为这个脚本正是你所需要的

var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)

回答by pota opt

Add rows:

添加行:

<html>
    <script>
        function addRow() {
            var table = document.getElementById('myTable');
            //var row = document.getElementById("myTable");
            var x = table.insertRow(0);
            var e = table.rows.length-1;
            var l = table.rows[e].cells.length;
            //x.innerHTML = "&nbsp;";

            for (var c=0, m=l; c < m; c++) {
                table.rows[0].insertCell(c);
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function addColumn() {
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";
            }
        }

        function deleteRow() {
            document.getElementById("myTable").deleteRow(0);
        }

        function deleteColumn() {
            // var row = document.getElementById("myRow");
            var table = document.getElementById('myTable');
            for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].deleteCell(0); // var table handle
            }
        }
    </script>

    <body>
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
            <tr id='myRow'>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </body>
</html>

And cells.

还有细胞。

回答by Pandiyan Cool

I have tried this, and this is working for me:

我试过这个,这对我有用:

var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);

回答by vaquar khan

You can use the following example:

您可以使用以下示例:

<table id="purches">
    <thead>
        <tr>
            <th>ID</th>
            <th>Transaction Date</th>
            <th>Category</th>
            <th>Transaction Amount</th>
            <th>Offer</th>
        </tr>
    </thead>

    <!--  <tr th:each="person: ${list}"    >
            <td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
            </tr>
    -->

    <tbody id="feedback">
    </tbody>
</table>

JavaScript file:

JavaScript 文件:

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/search",
    data: JSON.stringify(search),
    dataType: 'json',
    cache: false,
    timeout: 600000,
    success: function (data) {
        //  var json = "<h4>Ajax Response</h4><pre>"  + JSON.stringify(data, null, 4) + "</pre>";
        // $('#feedback').html(json);
        //
        console.log("SUCCESS: ", data);
        //$("#btn-search").prop("disabled", false);

        for (var i = 0; i < data.length; i++) {
            //$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
            $('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');

            alert(data[i].accountNumber)
        }
    },
    error: function (e) {
        var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
        $('#feedback').html(json);

        console.log("ERROR: ", e);
        $("#btn-search").prop("disabled", false);
    }
});

回答by Siddhartha Mahato

Add Column, Add Row, Delete Column, and Delete Row.

添加列、添加行、删除列和删除行。

The Simplest way

最简单的方法

function addColumn(myTable) {
    var table = document.getElementById(myTable);
    var row = table.getElementsByTagName('tr');
    for (i=0; i<row.length; i++) {
        row[i].innerHTML = row[i].innerHTML + '<td></td>';
    }
}

function deleterow(tblId)
{
      var table = document.getElementById(tblId);
      var row = table.getElementsByTagName('tr');
      if (row.length != '1') {
          row[row.length - 1].outerHTML = '';
      }
}

function deleteColumn(tblId)
{
    var allRows = document.getElementById(tblId).rows;
    for (var i=0; i<allRows.length; i++) {
        if (allRows[i].cells.length > 1) {
            allRows[i].deleteCell(-1);
        }
    }
}

function myFunction(myTable) {
    var table = document.getElementById(myTable);
    var row = table.getElementsByTagName('tr');
    var row = row[row.length-1].outerHTML;
    table.innerHTML = table.innerHTML + row;
    var row = table.getElementsByTagName('tr');
    var row = row[row.length-1].getElementsByTagName('td');
    for(i=0; i<row.length; i++) {
        row[i].innerHTML = '';
    }
}
table, td {
    border: 1px solid black;
    border-collapse: collapse;
}
td {
    cursor: text;
    padding: 10px;
}
td:empty:after {
    content: "Type here...";
    color: #CCCCCC;
}
<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <form>
            <p>
            <input type="button" value="+Column" onclick="addColumn('tblSample')">
            <input type="button" value="-Column" onclick="deleteColumn('tblSample')">
            <input type="button" value="+Row" onclick="myFunction('tblSample')">
            <input type="button" value="-Row" onclick="deleterow('tblSample')">
            </p>
            <table><tbody id="tblSample" contenteditable><tr><td></td></tr></tbody></table>
        </form>
    </body>

</html>