data 数据集
pId 当前点击数据的父级ID
应用场景
layui-tree 异步加载时 控制开合状态
下面这段代码是在 点击当前 DOM 获取数据的请求成功函数内
obj.children = res.datas; // 异步加载的数据
function init(data,pId){
var datas = data.map(function(item){
item.spread = false; // 初始化关闭所有
if(pId == item.id){
item.spread = true; // 当前数据父级为true
if(item.pId!=0){
// 找到上一级父级数据,再次递归 (这是重点)
init(parentTreeData,item.pId)
}
}// 注意不要加 else
if(item.children){
// 若一级数据没有当前点击数据,递归所有子集数据
item.children = init(item.children,pId)
}
return item
})
return datas;
}
init(parentTreeData,obj.pId)
obj.spread = true; // 当前点击数据打开
下面展示下数据结构
[ {
"children" : null,
"pId" : "1002",
"id" : "1310",
"title" : "xxxxx"
}, {
"children" : null,
"pId" : "1002",
"id" : "1311",
"title" : "xxxxx"
}, {
"children" : [ { } ], // 这种是有子集的
"pId" : "1002",
"id" : "1337",
"title" : "xxxxx"
} ]
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论