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

我是这样做的:

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

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


当前回答

<tr id="tablerow"></tr>

$('#tablerow').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);

所以,自从@Luke Bennett回答这个问题后,情况就发生了变化。这里有一个更新。

jQuery自1.4版(?)起自动检测您试图插入的元素(使用append()、prepend()、before()或after()方法中的任何一种)是否是<tr>,并将其插入到表中的第一个<tbody>中,如果不存在,则将其包装到新的<tbody中。

因此,是的,您的示例代码是可以接受的,并且可以与jQuery1.4+一起工作。;)

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

提示:通过innerHTML或.html()在html表中插入行在某些浏览器中是无效的(类似于IE9),在任何浏览器中使用.append(“<tr></tr>”)都不是很好的建议。最好和最快的方法是使用纯javascript代码。

要以这种方式与jQuery结合,只需添加类似于jQuery的新插件:

$.fn.addRow=function(index/*-1: add to end  or  any desired index*/, cellsCount/*optional*/){
    if(this[0].tagName.toLowerCase()!="table") return null;
    var i=0, c, r = this[0].insertRow((index<0||index>this[0].rows.length)?this[0].rows.length:index);
    for(;i<cellsCount||0;i++) c = r.insertCell(); //you can use c for set its content or etc
    return $(r);
};

现在在整个项目中使用它,类似于:

var addedRow = $("#myTable").addRow(-1/*add to end*/, 2);

试试这个:非常简单的方法

$('<tr><td>3</td></tr><tr><td>4</td></tr>').appendTo(“#myTable tbody”);<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js“></script><table id=“myTable”><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>

这可以使用jQuery的“last()”函数轻松完成。

$("#tableId").last().append("<tr><td>New row</td></tr>");