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

我是这样做的:

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

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


当前回答

我的解决方案:

//Adds a new table row
$.fn.addNewRow = function (rowId) {
    $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>');
};

用法:

$('#Table').addNewRow(id1);

其他回答

要在当前行的最后一行添加新行,可以使用如下方法

$('#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";

这是我的解决方案

$('#myTable').append('<tr><td>'+data+'</td><td>'+other data+'</td>...</tr>');

我尝试过最受欢迎的一种,但它对我不起作用,但下面的效果很好。

$('#mytable tr').last().after('<tr><td></td></tr>');

即使那里有一个雪橇,它也会起作用。

你建议的方法并不一定能给你带来你想要的结果——例如,如果你有一个tbody:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

您将得到以下结果:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

因此,我建议采用以下方法:

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

您可以在after()方法中包含任何内容,只要它是有效的HTML,包括上面示例中的多行。

更新:在最近使用此问题进行活动后,重新审视此答案。无眼是一个很好的评论,即DOM中总会有一个tbody;这是正确的,但前提是至少有一行。如果没有行,除非您自己指定了一行,否则不会有tbody。

DaRKoN_建议在tbody之后添加内容,而不是在最后一个tr之后添加内容。这解决了没有行的问题,但仍然不可靠,因为理论上可以有多个tbody元素,行将添加到每个元素中。

权衡一切,我不确定是否有一个单一的单线解决方案能够解决每一种可能的情况。您需要确保jQuery代码与标记相符。

我认为最安全的解决方案可能是确保您的表始终在标记中包含至少一个tbody,即使它没有行。在此基础上,您可以使用以下方法,无论您有多少行(也可以考虑多个tbody元素)都可以使用:

$('#myTable > tbody:last-child').append('<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);