layui树(tree)获取所有选中的节点id

时间:2025-04-02 16:17:54
<script> //渲染tree layui.use(['form', 'tree'], function () { var tree = layui.tree , form = layui.form; var inst1 = tree.render({ elem: '#roleTree' //绑定元素 , id: 'tree1' , data: [{ "id": 1, "title": "公司管理", "children": [{ "id": 4, "title": "人员列表", "children": [{ "id": 5, "title": "添加人员", "children": null, "spread": true, "checked": true }, {"id": 6, "title": "修改人员", "children": null, "spread": true, "checked": true}, { "id": 7, "title": "删除人员", "children": null, "spread": true, "checked": true }], "spread": true, "checked": null }], "spread": true, "checked": null }, { "id": 8, "title": "用户管理", "children": [{ "id": 9, "title": "用户列表", "children": [{ "id": 11, "title": "添加用户", "children": null, "spread": true, "checked": true }, {"id": 12, "title": "删除用户", "children": null, "spread": true, "checked": true}, { "id": 13, "title": "用户赋角色", "children": null, "spread": true, "checked": true }], "spread": true, "checked": null }, { "id": 10, "title": "角色列表", "children": [{ "id": 14, "title": "添加角色", "children": null, "spread": true, "checked": true }, {"id": 15, "title": "删除角色", "children": null, "spread": true, "checked": true}, { "id": 16, "title": "角色赋权", "children": null, "spread": true, "checked": true }], "spread": true, "checked": null }], "spread": true, "checked": null }] , showCheckbox: true }) ; // 监听点击按钮 $("#sub").click(function(){ //获取所有选中节点id数组 var checkedData = tree.getChecked('tree1'); //获取选中节点的数据 var nodeIds = new Array(); nodeIds = getCheckedId(checkedData); console.log(nodeIds); }); }); //获取所有选中的节点id function getCheckedId(data) { var id = ""; $.each(data, function (index, item) { if (id != "") { id = id + "," + item.id; } else { id = item.id; } //item 没有children属性 if (item.children != null) { var i = getCheckedId(item.children); if (i != "") { id = id + "," + i; } } }); return id; } </script>