picgo/static/js/table.js
2024-08-01 20:40:06 +08:00

49 lines
1.5 KiB
JavaScript

function Table(columns, data, actions, elementId) {
this.columns = columns
this.data = data
this.actions = actions
this.element = $(elementId)
}
Table.prototype.RenderTable = function () {
let self = this
// 创建表格元素
let $table = $('<table class="table table-bordered">');
// 创建表头
let $thead = $('<thead class="table-primary">');
let $theadRow = $('<tr>');
self.columns.forEach(function(col) {
$theadRow.append('<th>' + col + '</th>');
});
// 如果有操作按钮,添加操作列
if (self.actions.length > 0) {
$theadRow.append('<th>操作</th>');
}
$thead.append($theadRow);
$table.append($thead);
// 创建表体
let $tbody = $('<tbody>');
self.data.forEach(function(row) {
let $tr = $('<tr>');
row.forEach(function(cell) {
$tr.append('<td>' + cell + '</td>');
});
// 如果有操作按钮,添加操作单元格
if (self.actions.length > 0) {
let $actionTd = $('<td>');
self.actions.forEach(function(action) {
let $button = $('<button class="btn btn-' + action.class + ' btn-sm">' + action.label + '</button>');
$button.on('click', function() {
action.onClick(row);
});
$actionTd.append($button);
});
$tr.append($actionTd);
}
$tbody.append($tr);
});
$table.append($tbody);
// 将表格添加到目标元素中
self.element.html($table);
}