用layui生成一个树表格
时间: 2024-05-24 20:04:40 浏览: 86
可以使用 layui 提供的 treeTable 插件来生成一个树表格。下面是一个简单的示例:
1. 引入 layui 和 treeTable 插件的 CSS 和 JS 文件:
```html
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.7/css/layui.min.css">
<script src="https://cdn.staticfile.org/layui/2.5.7/layui.min.js"></script>
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/jquery-treegrid/0.2.0/js/jquery.treegrid.min.js"></script>
```
2. 在 HTML 中定义一个表格和相关的列:
```html
<table class="layui-table" id="demo" lay-filter="test"></table>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</button>
</div>
</script>
<script type="text/html" id="iconTpl">
{{# if(d.children){ }}
<i class="layui-icon layui-icon-triangle-r"></i>
{{# } }}
</script>
```
3. 在 JS 中初始化 treeTable:
```javascript
layui.use(['table', 'layer', 'form', 'jquery', 'treeTable'], function () {
var table = layui.table;
var layer = layui.layer;
var form = layui.form;
var $ = layui.jquery;
var treeTable = layui.treeTable;
// 渲染表格
treeTable.render({
elem: '#demo',
treeId: 'id', // 树形id字段名称
treeUpId: 'parentId', // 树形父id字段名称
treeShowName: 'name', // 树形名称字段名称
cols: [[
{type: 'numbers'},
{field: 'name', title: '名称', templet: '#iconTpl'},
{field: 'url', title: '链接'},
{field: 'sort', title: '排序'},
{title: '操作', width: 180, align: 'center', toolbar: '#toolbarDemo'}
]],
data: [
{
"id": "1",
"name": "目录1",
"url": "",
"parentId": "0",
"sort": "1",
"children": [
{
"id": "2",
"name": "目录1-1",
"url": "http://www.baidu.com",
"parentId": "1",
"sort": "1",
"children": [
{
"id": "3",
"name": "目录1-1-1",
"url": "http://www.baidu.com",
"parentId": "2",
"sort": "1",
"children": null
}
]
},
{
"id": "4",
"name": "目录1-2",
"url": "http://www.baidu.com",
"parentId": "1",
"sort": "2",
"children": null
}
]
},
{
"id": "5",
"name": "目录2",
"url": "http://www.baidu.com",
"parentId": "0",
"sort": "2",
"children": [
{
"id": "6",
"name": "目录2-1",
"url": "http://www.baidu.com",
"parentId": "5",
"sort": "1",
"children": null
}
]
}
]
});
// 监听工具条
table.on('tool(test)', function (obj) {
var data = obj.data;
if (obj.event === 'add') {
// 添加操作
} else if (obj.event === 'delete') {
// 删除操作
}
});
});
```
以上示例代码可以生成一个带有树形结构的表格,并且可以添加、删除数据。你可以根据实际需求修改表格的列数和数据项。
阅读全文