我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
当前回答
要在当前行的最后一行添加新行,可以使用如下方法
$('#yourtableid tr:last').after('<tr>...</tr><tr>...</tr>');
您可以如上所述追加多行。也可以像这样添加内部数据
$('#yourtableid tr:last').after('<tr><td>your data</td></tr>');
用另一种方式你可以这样做
let table = document.getElementById("tableId");
let row = table.insertRow(1); // pass position where you want to add a new row
//then add cells as you want with index
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
let cell3 = row.insertCell(3);
//add value to added td cell
cell0.innerHTML = "your td content here";
cell1.innerHTML = "your td content here";
cell2.innerHTML = "your td content here";
cell3.innerHTML = "your td content here";
其他回答
<table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
<tr>...</tr>
</table>
使用javascript函数编写
document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';
尼尔的回答是迄今为止最好的。然而,事情很快就会变得一团糟。我的建议是使用变量来存储元素并将其附加到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);
您可以使用这个很棒的jQuery添加表行函数。它适用于有<tbody>但没有的表。它还考虑了最后一行表格的列跨度。
下面是一个示例用法:
// One table
addTableRow($('#myTable'));
// add table row to number of tables
addTableRow($('.myTables'));
我遇到了一些相关的问题,试图在单击的行之后插入一个表行。除了.after()调用对最后一行不起作用之外,一切都很好。
$('#traffic tbody').find('tr.trafficBody).filter(':nth-child(' + (column + 1) + ')').after(insertedhtml);
我想出了一个非常不整洁的解决方案:
按如下方式创建表(每行的id):
<tr id="row1"> ... </tr>
<tr id="row2"> ... </tr>
<tr id="row3"> ... </tr>
等
然后:
$('#traffic tbody').find('tr.trafficBody' + idx).after(html);
<tr id="tablerow"></tr>
$('#tablerow').append('<tr>...</tr><tr>...</tr>');