通过递归把ztree的复杂数据模式转换成简单数据模式
复杂数据结构简单数据结构
完整代码如下:
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title>可选配件</title>
<link rel="stylesheet" href="css/zTreeStyle.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.ztree.all.js"></script>
<style type="text/css">
.ztree{width:300px;height:300px;margin:20px auto;background-color:#CCCCCC;overflow-y:scroll;font-size:14px;}
</style>
</head>
<body>
<div class="ztree" id="ztree">
</div>
<script type="text/javascript">
var Json1=[{"UI":"配件,单选目录","Name":"路轨目录","Data":470517008,"State":0,"Child":[{"UI":"配件","Name":"三节滚珠路轨","Data":470517072,"State":1,"Child":[]},{"UI":"配件","Name":"隐藏托底阻尼路轨","Data":470517200,"State":0,"Child":[]}]},{"UI":"单选目录","Name":"抽面目录","Data":470516880,"State":0,"Child":[{"UI":"配件","Name":"抽面(横纹)","Data":470516368,"State":1,"Child":[]},{"UI":"配件","Name":"抽面(竖纹)","Data":470516560,"State":0,"Child":[]}]},{"UI":"多选目录","Name":"拉手目录","Data":470516944,"State":1,"Child":[{"UI":"单选目录","Name":"YL232","Data":0,"State":1,"Child":[{"Name":"吊环拉手","Data":0,"State":0,"Child":[]},{"Name":"圆点拉手","Data":0,"State":1,"Child":[]}]},{"UI":"多选目录","Name":"YL295","Data":0,"State":0,"Child":[{"Name":"G0501-64","Data":0,"State":1,"Child":[]},{"Name":"G0501-192","Data":0,"State":0,"Child":[]}]},{"Name":"吊环拉手","Data":0,"State":1,"Child":[]},{"Name":"圆点拉手","Data":0,"State":0,"Child":[]},{"Name":"YL059","Data":0,"State":1,"Child":[]},{"Name":"G0501-64","Data":0,"State":1,"Child":[]},{"Name":"G0501-192","Data":0,"State":0,"Child":[]}]}];
var zNodes=[];
//递归数据,处理成简单数据模式
function ZNodesEach(jsonA,PID,DIR){
for (var i=0;i<jsonA.length;i++){
var obj={};
if("UI" in jsonA[i]){
obj.type=jsonA[i].UI;
if(jsonA[i].UI.indexOf("目录")>=0){
obj.isParent=true;
}else{
obj.isParent=false;
}
}else{
obj.type="配件";
obj.isParent=false;
}
obj.pId=PID;
if(obj.pId==0){
DIR=0;
}
obj.dir=DIR;
obj.id=jsonA[i].Name+DIR;
obj.checked=jsonA[i].State;
if(obj.checked==1){
obj.name="<div class='Pro"+DIR+"' style='display:inline-block;'><span class='ProName"+DIR+"'>"+jsonA[i].Name+"</span><span class='ProNum' onclick='selectNum(this)'>1</span><span><input onclick='checkPic(this)' type='checkbox' class='ProCheck' checked='true'/></span></div>";
}else{
obj.name="<div class='Pro"+DIR+"' style='display:inline-block;'><span class='ProName"+DIR+"'>"+jsonA[i].Name+"</span><span class='ProNum' onclick='selectNum(this)'>1</span><span><input onclick='checkPic(this)' type='checkbox' class='ProCheck'/></span></div>";
}
zNodes.push(obj);
if(jsonA[i].Child!=''){
var Cdir=DIR+1;
var newNode=jsonA[i].Child;
ZNodesEach(newNode,obj.id,Cdir);
}
}
}
ZNodesEach(Json1,0,0);
console.log(zNodes);
var setting = {
edit: {
enable: false,
showRemoveBtn: false,
showRenameBtn: false
},
view: {
nameIsHTML: true
},
data: {
simpleData:{
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: 0
}
}
};
//页面加载
$(function(){
$.fn.zTree.init($("#ztree"), setting,zNodes);
})
</script>
</body>
</html>