[2024-07-20](UPDATE): 通用表格封装
This commit is contained in:
parent
b239a8ea95
commit
aabcf8df1e
49
static/js/table.js
Normal file
49
static/js/table.js
Normal file
@ -0,0 +1,49 @@
|
||||
function Table(columns, data, actions, elementId) {
|
||||
this.columns = columns
|
||||
this.data = data
|
||||
this.actions = actions
|
||||
this.element = $(elementId)
|
||||
}
|
||||
|
||||
Table.prototype.Generic = 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);
|
||||
}
|
@ -2,9 +2,41 @@
|
||||
{{end}}
|
||||
|
||||
{{define "content"}}
|
||||
<h1 class="h2">User</h1>
|
||||
<p>User page content goes here.</p>
|
||||
<div id="user-table"></div>
|
||||
{{end}}
|
||||
|
||||
{{define "script"}}
|
||||
<script src="/static/js/table.js"></script>
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
// 示例数据
|
||||
let columns = ['ID', '名称', '年龄'];
|
||||
let data = [
|
||||
[1, '张三', 25],
|
||||
[2, '李四', 30],
|
||||
[3, '王五', 28]
|
||||
];
|
||||
|
||||
// 操作按钮配置
|
||||
let actions = [
|
||||
{
|
||||
label: '编辑',
|
||||
class: 'primary',
|
||||
onClick: function(row) {
|
||||
alert('编辑:' + row[1]);
|
||||
}
|
||||
},
|
||||
{
|
||||
label: '删除',
|
||||
class: 'danger',
|
||||
onClick: function(row) {
|
||||
alert('删除:' + row[1]);
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
let table = new Table(columns, data, actions, "#user-table")
|
||||
table.Generic()
|
||||
})
|
||||
</script>
|
||||
{{end}}
|
Loading…
Reference in New Issue
Block a user