What is the best method in jQuery to add an additional row to a table as the last row?
Is this acceptable?
$(\'#myTable\').append(\'
-
In my opinion the fastest and clear way is
//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('hello> ');
here is demo Fiddle
Also I can recommend a small function to make more html changes
//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] : '';
});
}
}());
If you use my string composer you can do this like
var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = ''+
'{{id}} '+
'{{name}} '+
'{{phone}} '+
' ';
//Add row
table.append(row.compose({
'id': 3,
'name': 'Lee',
'phone': '123 456 789'
}));
Here is demo
Fiddle
- 热议问题