gpt4 book ai didi

javascript - 如何使用动态生成的表动态添加行

转载 作者:行者123 更新时间:2023-12-02 14:29:41 26 4
gpt4 key购买 nike

我有以下代码。

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);

它会产生这样的结果:

http://jsfiddle.net/bytg16k6/

我需要一个按钮来动态地添加新行,但我坚持这样做

最佳答案

您的表有一个类(如果您有多个具有该类的表,则可以有一个 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/

请注意,上面的代码只是执行此操作的方法示例。

关于javascript - 如何使用动态生成的表动态添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com