我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
当前回答
由于我也有一种方法在最后或任何特定位置添加行,所以我认为我也应该分享这一点:
首先找出行的长度:
var r=$("#content_table").length;
然后使用以下代码添加行:
$("#table_id").eq(r-1).after(row_html);
其他回答
上面的答案非常有用,但当学生参考此链接从表单中添加数据时,他们通常需要一个示例。
我想提供一个示例,从from获取输入,并使用.after()使用字符串插值将tr插入到表中。
function add(){
let studentname = $("input[name='studentname']").val();
let studentmark = $("input[name='studentmark']").val();
$('#student tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);
}
函数add(){let studentname=$(“input[name='studentname']”).val();let studentmark=$(“input[name='studentmark']”).val();$('#student-tr:last').after(`<tr><td>${studentname}</td><td>${studentmark}</td></tr>`);}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><!DOCTYPE html><html><head><style>表{字体系列:arial,sans-serif;边界塌陷:塌陷;宽度:100%;}td,第{边框:1px实心#dddddd;文本对齐:左侧;填充:8px;}tr:第n个孩子(偶数){背景色:#dddddd;}</style></head><body><表单><input-type='text'name='studentname'/><input-type='text'name='studentmark'/><input-type='button'onclick=“add()”value=“add new”/></form><table id=“学生”><thead><th>名称</th><th>标记</th></thead></table></body></html>
// 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);
<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'
}));
这里是演示不停摆弄
当表中没有任何行时,我使用这种方式,而且每一行都非常复杂。
style.css:
...
#templateRow {
display:none;
}
...
xxx.html
...
<tr id="templateRow"> ... </tr>
...
$("#templateRow").clone().removeAttr("id").appendTo( $("#templateRow").parent() );
...