树形结构在实际开发中很长用到,比如部门管理,权限菜单等。因为用树形结构来展示会显的很清晰明了。
使用 ztree插件,制作树形菜单
zTree 是一个依靠 jQuery实现的多功能 “树插件”。优异的性能、灵活的配置、多种功能的组合是zTree 最大优点。
<style>
#treeDemo {
width: 100%;
height: auto;
font-size: 2em;
}
</style>
</head>
<body>
<div>
<button type="button" id="c_all" class="layui-btn layui-btn-primary">全选/取消全选</button>
<ul style="" id="treeDemo" class="ztree"></ul>
</div>
</body>
<SCRIPT>
var zTreeObj;
// zTree 的参数配置
var setting = {
check: {
//false不显示复选框true显示
enable: true
},
data: {
simpleData: {
enable: true
}
}
};
// zTree 的数据属性
var zNodes =[
{id: 1, pId: 0, name: "一级菜单1"},
{id: 2, pId: 0, name: "一级菜单2"},
{id: 3, pId: 0, name: "一级菜单3"},
{id: 4, pId: 0, name: "一级菜单4"},
{id: 5, pId: 0, name: "一级菜单5"},
{id: 6, pId: 0, name: "一级菜单6"},
{id: 7, pId: 1, name: "二级菜单1"},
{id: 8, pId: 1, name: "二级菜单1"},
{id: 9, pId: 1, name: "二级菜单1"},
{id: 10, pId: 2, name: "二级菜单2"},
{id: 11, pId: 2, name: "二级菜单2"},
{id: 12, pId: 2, name: "二级菜单2"},
{id: 13, pId: 3, name: "二级菜单3"},
{id: 14, pId: 3, name: "二级菜单3"},
{id: 15, pId: 3, name: "二级菜单3"},
{id: 16, pId: 4, name: "二级菜单4"},
{id: 17, pId: 4, name: "二级菜单4"},
{id: 18, pId: 4, name: "二级菜单4"},
{id: 19, pId: 5, name: "二级菜单5"},
{id: 20, pId: 5, name: "二级菜单5"},
{id: 21, pId: 5, name: "二级菜单5"},
{id: 22, pId: 6, name: "二级菜单6"},
{id: 23, pId: 6, name: "二级菜单6"},
{id: 24, pId: 6, name: "二级菜单6"},
];
$(document).ready(function () {
zTreeObj=$.fn.zTree.init($("#treeDemo"), setting, zNodes);
zTreeObj.expandAll(true);
});
// $.ajax({
// url:"", //请求的url地址
// dataType:"json", //返回格式为json
// async:true,//请求是否异步,默认为异步,这也是ajax重要特性
// data:, //参数值
// type:"POST",
// success:function(res){
// 这里调用接口返回数据字段必须是{id: 24, pId: 6, name: "二级菜单6"},才会渲染成功
// zNodes = res.data
// $(document).ready(function () {
// zTreeObj=$.fn.zTree.init($("#treeDemo"), setting, zNodes);
// zTreeObj.expandAll(true);
// });
// }
// });
$('#c_all').on('click',function (e) {
var zTree = $.fn.zTree.getZTreeObj("treeDemo");//得到tree对象 treeMenu是我的treeid
var node = zTree.getNodes();//得到全部节点
var nodes = zTree.transformToArray(node);//全部节点转换成数组array
var checkNode = zTree.getCheckedNodes().length;//得到被选中的节点数量,zTree.getCheckedNodes()和zTree.getCheckedNodes(true)一样,可以传参(true/false),默认是true
if (checkNode < nodes.length) {//已选中的节点数小于总数 - 全选
$('#all').prop('checked', true)
zTree.checkAllNodes(true);//给全部节点设置为true
} else{
zTree.checkAllNodes(false);//给全部节点设置为false
}
});
</script>