在jQuery中添加表格行
技术背景
在网页开发中,动态添加表格行是一个常见的需求。jQuery 作为一个广泛使用的 JavaScript 库,提供了便捷的方法来操作 DOM 元素,能够轻松实现向表格中添加行的功能。
实现步骤
1. 基本的添加行方法
如果表格有 tbody
标签,可使用以下方法在最后一行后添加新行:
1
| $('#myTable tr:last').after('<tr>...<tr>');
|
2. 确保在 tbody
中添加行
为了确保新行被添加到 tbody
中,可使用以下代码:
1
| $('#myTable > tbody:last-child').append('<tr>...<tr>');
|
3. 通用的添加行方法
考虑到各种情况,可使用以下通用方法:
1 2 3 4 5 6 7 8
| function add_new_row(table, rowcontent) { if ($(table).length > 0) { if ($(table + ' > tbody').length == 0) $(table).append('<tbody />'); ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent); } }
add_new_row('#myTable','<tr><td>my new row</td></tr>');
|
4. 使用模板添加行
如果行内容比较复杂,可使用模板的方式添加行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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>';
table.append(row.compose({ 'id': 3, 'name': 'Lee', 'phone': '123 456 789' }));
|
核心代码
jQuery 方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
var row = $('<tr />', {}).appendTo("#table_id"); $('<td />', { 'text': 'column1' }).appendTo(row); $('<td />', { 'text': 'column2', 'style': 'min-width:100px;' }).appendTo(row);
$.fn.addNewRow = function (rowId) { $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>'); };
$('#Table').addNewRow(id1);
|
JavaScript 原生方式
1
| document.getElementById("myTable").insertRow(-1).innerHTML = '<td>1</td><td>2</td>';
|
最佳实践
- 确保表格中有
tbody
标签,这样可以避免一些不必要的问题。 - 使用模板字符串可以使代码更易维护,尤其是当行内容复杂时。
- 对于复杂的表格操作,可封装成函数,提高代码的复用性。
常见问题
1. 新行添加到了 tfoot
而不是 tbody
如果表格中同时存在 tbody
和 tfoot
,直接使用 append
可能会将新行添加到 tfoot
中。解决方法是明确指定 tbody
:
1
| $("#myTable > tbody").append("<tr><td>row content</td></tr>");
|
2. 嵌套表格问题
如果表格中有嵌套表格,新行可能会被添加到嵌套表格中。可使用以下方法避免:
1 2 3 4 5 6
| function add_new_row(table, rowcontent) { if ($(table).length > 0) { if ($(table + ' > tbody').length == 0) $(table).append('<tbody />'); ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent); } }
|
3. .after()
方法在最后一行不工作
如果使用 .after()
方法在最后一行后添加行不工作,可考虑使用其他方法,如直接在 tbody
中 append
新行。