我使用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);

其他回答

尼尔的回答是迄今为止最好的。然而,事情很快就会变得一团糟。我的建议是使用变量来存储元素并将其附加到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);

当表中没有任何行时,我使用这种方式,而且每一行都非常复杂。

style.css:

...
#templateRow {
  display:none;
}
...

xxx.html

...
<tr id="templateRow"> ... </tr>
...

$("#templateRow").clone().removeAttr("id").appendTo( $("#templateRow").parent() );

...
var html = $('#myTableBody').html();
html += '<tr><td>my data</td><td>more data</td></tr>';
$('#myTableBody').html(html);

or

$('#myTableBody').html($('#myTableBody').html() + '<tr><td>my data</td><td>more data</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>';
<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

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

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