我使用jQuery向表中添加一行作为最后一行。

我是这样做的:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?


当前回答

我是这样解决的。

使用jquery

$('#tab').append($('<tr>')
    .append($('<td>').append("text1"))
    .append($('<td>').append("text2"))
    .append($('<td>').append("text3"))
    .append($('<td>').append("text4"))
  )

一小条

$('#tab').append($('<tr>')追加($('<td>')追加(“text1”))追加($('<td>')追加(“text2”))追加($('<td>')追加(“text3”))追加($('<td>')追加(“text4”)))<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><table id=“tab”><tr><th>名字</th><th>姓氏</th>年龄</th><th>城市</th></tr><tr><td>吉尔</td><td>史密斯</td><td>50个</td><td>纽约</td></tr></table>

其他回答

对于此处发布的最佳解决方案,如果最后一行上有一个嵌套表,则新行将添加到嵌套表而不是主表。快速解决方案(考虑带/不带tbody的表和带嵌套表的表):

function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}

用法示例:

add_new_row('#myTable','<tr><td>my new row</td></tr>');
<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

使用javascript函数编写

document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';

您可以使用这个很棒的jQuery添加表行函数。它适用于有<tbody>但没有的表。它还考虑了最后一行表格的列跨度。

下面是一个示例用法:

// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));

尼尔的回答是迄今为止最好的。然而,事情很快就会变得一团糟。我的建议是使用变量来存储元素并将其附加到DOM层次结构中。

HTML

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

JAVASCRIPT语言

// Reference to the table body
var body = $("#tableID").find('tbody');

// Create a new row element
var row = $('<tr>');

// Create a new column element
var column = $('<td>');

// Create a new image element
var image = $('<img>');
image.attr('src', 'img.png');
image.text('Image cell');

// Append the image to the column element
column.append(image);
// Append the column to the row element
row.append(column);
// Append the row to the table body
body.append(row);
<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

您可以缓存页脚变量并减少对DOM的访问(注意:使用假行而不是页脚可能会更好)。

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")