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

我是这样做的:

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

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


当前回答

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

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

其他回答

所以,自从@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>');

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

$("#tableId").last().append("<tr><td>New row</td></tr>");
    // Create a row and append to table
    var row = $('<tr />', {})
        .appendTo("#table_id");

    // Add columns to the row. <td> properties can be given in the JSON
    $('<td />', {
        'text': 'column1'
    }).appendTo(row);

    $('<td />', {
        'text': 'column2',
        'style': 'min-width:100px;'
    }).appendTo(row);

提示:通过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);

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

style.css:

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

xxx.html

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

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

...