tree.getchecked() 是唯一可靠入口,但必须配置 id 且递归提取才能获得纯 id 数组;不设 id 会报错,返回值为嵌套节点对象,需手动递归扁平化获取 id 列表。
tree.getchecked() 是唯一可靠入口,但必须配合 id 配置和递归提取才能拿到纯 id 数组;不设 id 会直接报 "cannot read properties of undefined (reading 'getchecked')"。
必须先确认 tree.render() 里写了 id
Layui 的树组件 API(比如 getChecked)依赖显式声明的 id 字段来定位实例。只写 elem: '#test1' 不够,id: 'test1' 缺一不可 —— 否则所有方法调用都会失败。
-
id值必须和elem选择器去掉#后完全一致(例如elem: '#roleTree'→id: 'roleTree') - 渲染后不能靠 DOM ID 推断,Layui 内部是用
id做实例注册键的 - 没配
id时tree.getChecked('xxx')返回undefined,不是空数组
tree.getChecked() 返回的是节点对象,不是 ID 列表
调用 tree.getChecked('roleTree') 得到的是一个嵌套结构的对象数组,每个元素含 id、title、children 等字段,**不自动扁平化,也不过滤掉未勾选的子节点**。你得自己递归遍历。
- 返回值结构和原始
data格式一致,只是只包含被勾选的分支 - 即使父节点没被勾选,只要某个子节点被勾选了,它也会出现在结果里
- 如果要用
type: 'leaf'只取叶子节点,得明确传第二个参数:tree.getChecked('roleTree', {type: 'leaf'})
递归提取 ID 的最小可行代码
别用 jQuery 的 $.each 套娃,原生 forEach + 递归更稳,也避免 item.children !== null 这类易错判断(实际可能是 undefined 或 [])。
function getCheckedIds(nodes) {
const ids = [];
(function walk(arr) {
if (!Array.isArray(arr)) return;
arr.forEach(node => {
ids.push(node.id);
if (Array.isArray(node.children) && node.children.length) {
walk(node.children);
}
});
})(nodes);
return ids;
}
// 使用示例
const checkedNodes = tree.getChecked('roleTree');
const idList = getCheckedIds(checkedNodes); // → [5, 6, 7, 11, 12, 13, ...]
注意:这个函数只处理 getChecked() 的输出,不是原始树数据;如果原始数据里有 checked: true 但 UI 没刷新,getChecked() 也不会包含它 —— 它读的是当前渲染状态,不是数据源快照。










