[英]How to dynamically add rows with a dynamically generated table
我有以下代碼。
arrayToTable = function(data, options = {}){
var table = $('<table />'),
thead,
tfoot,
rows = [],
row,
i, j,
defaults = {
th: true, // should we use th elemenst for the first row
thead: false, //should we incldue a thead element with the first row
tfoot: false, // should we include a tfoot element with the last row
attrs: {} // attributes for the table element, can be used to
}
options = $.extend(defaults, options);
table.attr(options.attrs)
// loop through all the rows, we will deal with tfoot and thead later
for(i = 0; i < data.length; i++){
row = $('<tr />');
for(j = 0; j < data[i].length; j++){
if(i == 0 && options.th){
row.append($('<th />').html(data[i][j]));
}else{
row.append($('<td />').html("<input type='text' name='fname'>"));
}
}
rows.push(row);
}
// if we want a thead use shift to get it
if(options.thead){
thead = rows.shift();
thead = $('<thead />').append(thead);
table.append(thead);
}
// if we want a tfoot then pop it off for later use
if(options.tfoot){
tfoot = rows.pop();
}
// add all the rows
for (i = 0; i < rows.length; i++) {
table.append(rows[i]);
};
// and finally add the footer if needed
if(options.tfoot){
tfoot = $('<tfoot />').append(tfoot);
table.append(tfoot);
}
return table;
}
var data = [
['Name', 'Age', 'Email'],
['John Doe', '27', 'john@doe.com'],
['Jane Doe', '29', 'jane@doe.com']
];
var table = arrayToTable(data, {
thead: true,
attrs: {class: 'table'}
})
$('body').append(table);
它產生了這個:
我需要一個按鈕向其動態添加新行,但是我仍然堅持
您的表有一個類(如果您有多個此類,可以有一個ID),然后單擊帶有“ add-row”類的按鈕可以使用以下代碼:
$('.add-row').on('click', function () {
$('.table').append('<tr><td>test</td><td>test</td><td>test</td></tr>');
});
http://jsfiddle.net/bytg16k6/1/
請注意,上面的代碼只是實現此目的的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.