toTree:function(treeDatas) { var that = this; var rs = []; for(var i=0; i<treeDatas.length; i++) { var pid = -1; if(treeDatas[i].hasOwnProperty("pid")){ pid = treeDatas[i].pid; } rs.push({id: treeDatas[i].id, name: treeDatas[i].subjectName, pid: pid, code: treeDatas[i].subjectNo}); } //获取容器对象 var selectbox = document.getElementById("selectbox"); var tree = that.listToTree(rs,-1);//调用函数,传入要转换的list数组,和树中顶级元素的pid //调用函数,并将结构出入到下拉框容器中 selectbox.innerHTML = that.creatSelectTree(tree); }, listToTree:function(list,pid) { var that = this; var ret = [];//一个存放结果的临时数组 for(var i in list) { if(list[i].pid == pid) {//如果当前项的父id等于要查找的父id,进行递归 list[i].children = that.listToTree(list, list[i].id); ret.push(list[i]);//把当前项保存到临时数组中 } } return ret;//递归结束后返回结果 }, preFlag:"+",//前缀符号,用于显示父子关系,这里可以使用其它符号 creatSelectTree:function(d){ var that = this; var option=""; for(var i=0;i<d.length;i++){ if(d[i].children.length){//如果有子集 option += "<option value=‘" + d[i].id + "‘>" + that.preFlag + d[i].name + "</option>"; that.preFlag += "-";//前缀符号加一个符号 option += that.creatSelectTree(d[i].children);//递归调用子集 that.preFlag = that.preFlag.slice(0,that.preFlag.length - 1);//每次递归结束返回上级时,前缀符号需要减一个符号 }else{//没有子集直接显示 option += "<option value=‘"+d[i].id+"‘>" + that.preFlag + d[i].name + "</option>"; } } return option;//返回最终html结果 }
原文地址:http://2091535.blog.51cto.com/2081535/1839831