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

其他回答

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

使用javascript函数编写

document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';

在我看来,最快和明确的方法是

//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');

//Then if no tbody just select your table 
var table = tbody.length ? tbody : $('#myTable');

//Add row
table.append('<tr><td>hello></td></tr>');

这是演示Fiddle

此外,我还可以推荐一个小函数来进行更多的html更改

//Compose template string
String.prototype.compose = (function (){
var re = /\{{(.+?)\}}/g;
return function (o){
        return this.replace(re, function (_, k){
            return typeof o[k] != 'undefined' ? o[k] : '';
        });
    }
}());

如果你用我的弦乐器,你可以这样做

var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = '<tr>'+
    '<td>{{id}}</td>'+
    '<td>{{name}}</td>'+
    '<td>{{phone}}</td>'+
'</tr>';


//Add row
table.append(row.compose({
    'id': 3,
    'name': 'Lee',
    'phone': '123 456 789'
}));

这里是演示不停摆弄

这是我的解决方案

$('#myTable').append('<tr><td>'+data+'</td><td>'+other 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);

如果你有一个<tbody>和一个<tfoot>呢?

例如:

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>

然后它将在页脚中插入新行,而不是插入正文。

因此,最好的解决方案是包含<tbody>标记并使用.append,而不是.after。

$("#myTable > tbody").append("<tr><td>row content</td></tr>");