Javascript 如何使用动态生成的表动态添加行
我有以下代码Javascript 如何使用动态生成的表动态添加行,javascript,jquery,Javascript,Jquery,我有以下代码 arrayToTable = function(data, options = {}){ var table = $('<table />'), thead, tfoot, rows = [], row, i, j, defaults = { th: true, // should we use th elemenst for the firs
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);
arrayToTable=函数(数据,选项={}){
变量表=$(''),
thead,
特富特,
行=[],
一行
i、 j,
默认值={
th:true,//我们应该在第一行使用th elemenst吗
thead:false,//我们应该在第一行中包含一个thead元素吗
tfoot:false,//我们应该在最后一行包含一个tfoot元素吗
属性:{}//table元素的属性,可用于
}
选项=$.extend(默认值,选项);
table.attr(options.attrs)
//循环遍历所有行,稍后我们将处理tfoot和thead
对于(i=0;i
它产生了这样的结果:
我需要一个按钮来平日向其中添加新行,但我坚持认为,您的表有一个类(如果您有多个此类的表,则可以有一个id),然后单击一个类为“添加行”的按钮即可使用以下代码:
$('.add-row').on('click', function () {
$('.table').append('<tr><td>test</td><td>test</td><td>test</td></tr>');
});
$('.add row')。在('click',函数(){
$('.table').append('testtest');
});
请注意,上面的代码只是实现此目的的一个示例。您的表有一个类(如果有多个表有此类,则可以有一个id),然后单击带有类“添加行”的按钮,即可使用以下代码:
$('.add-row').on('click', function () {
$('.table').append('<tr><td>test</td><td>test</td><td>test</td></tr>');
});
$('.add row')。在('click',函数(){
$('.table').append('testtest');
});
请注意,上面的代码只是实现此目的的一个示例