layui树形组件回显
时间: 2023-08-27 21:07:10 浏览: 92
layui组件之树形下拉框
5星 · 资源好评率100%
1.在页面中引入layui的css和js文件:
```
<link rel="stylesheet" href="/layui/css/layui.css">
<script src="/layui/layui.js"></script>
```
2.创建一个div作为树形组件的容器:
```
<div id="tree"></div>
```
3.定义树形组件的数据:
```
var treeData = [{
"id": 1,
"name": "节点1",
"children": [{
"id": 11,
"name": "节点1-1"
}, {
"id": 12,
"name": "节点1-2"
}]
}, {
"id": 2,
"name": "节点2",
"children": [{
"id": 21,
"name": "节点2-1"
}, {
"id": 22,
"name": "节点2-2"
}]
}];
```
4.使用layui.tree组件创建树形结构:
```
layui.use(['tree'], function(){
var tree = layui.tree;
tree.render({
elem: '#tree',
data: treeData,
id: 'treeId',
showCheckbox: true,
accordion: true,
checkArr: [1, 11] //默认勾选节点1和节点1-1
});
});
```
其中,id为树形组件的唯一标识,showCheckbox表示是否显示复选框,accordion表示是否开启手风琴模式(只展开一个节点),checkArr表示默认勾选的节点的id数组。
5.获取勾选的节点:
```
var checkedData = layui.tree.getChecked('treeId');
```
其中,treeId为树形组件的id。
6.将勾选的节点id数组转换成树形组件需要的格式:
```
var checkedIds = [];
for (var i = 0; i < checkedData.length; i++) {
checkedIds.push(checkedData[i].id);
}
var checkedArr = layui.tree.ConvertToArr('treeId', checkedIds);
```
7.将勾选的节点回显到树形组件中:
```
layui.use(['tree'], function(){
var tree = layui.tree;
tree.render({
elem: '#tree',
data: treeData,
id: 'treeId',
showCheckbox: true,
accordion: true,
checkArr: checkedArr //勾选之前已经勾选的节点
});
});
```
完整代码如下:
```
<link rel="stylesheet" href="/layui/css/layui.css">
<script src="/layui/layui.js"></script>
<div id="tree"></div>
<script>
var treeData = [{
"id": 1,
"name": "节点1",
"children": [{
"id": 11,
"name": "节点1-1"
}, {
"id": 12,
"name": "节点1-2"
}]
}, {
"id": 2,
"name": "节点2",
"children": [{
"id": 21,
"name": "节点2-1"
}, {
"id": 22,
"name": "节点2-2"
}]
}];
layui.use(['tree'], function(){
var tree = layui.tree;
tree.render({
elem: '#tree',
data: treeData,
id: 'treeId',
showCheckbox: true,
accordion: true,
checkArr: [1, 11] //默认勾选节点1和节点1-1
});
var checkedData = layui.tree.getChecked('treeId');
var checkedIds = [];
for (var i = 0; i < checkedData.length; i++) {
checkedIds.push(checkedData[i].id);
}
var checkedArr = layui.tree.ConvertToArr('treeId', checkedIds);
tree.render({
elem: '#tree',
data: treeData,
id: 'treeId',
showCheckbox: true,
accordion: true,
checkArr: checkedArr //勾选之前已经勾选的节点
});
});
</script>
```
阅读全文