使用回调函数实现联动
直接上代码 :
直接看最下面:
<!DOCTYPE HTML> <html> <head> <title>递归实现联动</title> <meta charset="utf-8" /> </head> <body> <div id="category"> </div> </body> <script> /*使用 HTML DOM 的方式实现联动菜单*/ var build=[ {"id":10,"name":'建筑业企业资质',"children":[ {"id":101,"name":'专业承包',"children":[ {"id":1020,"name":'地基基础工和专业承包',"children":[ {"id":10201,"name":'一级',"children":[ {"id":1020101,"name":'城市园林绿化资质',"children":[ {"id":102010103,"name":'信息系统集成及服务',"children":[ {"id":102010102,"name":'递归'} ]} ]}, {"id":1020102,"name":'递归'}, {"id":1020103,"name":'递归'}, {"id":1020104,"name":'递归'}, ]}, {"id":10202,"name":'一级以下'}, {"id":10203,"name":'二级以上'}, {"id":10204,"name":'二级以下'}, {"id":10205,"name":'三级'}, {"id":10206,"name":'三级以上'}, ]}, {"id":1029,"name":'钢结构工程专业承包',"children":[ {"id":10201,"name":'一级',"children":[ {"id":1020101,"name":'递归',"children":[ {"id":102010101,"name":'递归',"children":[ {"id":102010103,"name":'递归',"children":[ {"id":102010102,"name":'递归'} ]} ]}, {"id":102010102,"name":'递归'} ]}, {"id":1020102,"name":'递归'}, {"id":1020103,"name":'递归'}, {"id":1020104,"name":'递归'}, ]}, {"id":10202,"name":'一级以下'}, {"id":10203,"name":'二级以上'}, {"id":10204,"name":'二级以下'}, {"id":10205,"name":'三级'}, {"id":10206,"name":'三级以上'}, ]}, ]}, ]}, ]; function constructionLibrary(build){ var selectChange=document.createElement("select"); category.appendChild(selectChange); // 设置默认头 var opt=new Option("---请选择---",-1); selectChange.appendChild(opt); var frag=document.createDocumentFragment(); for(var i=0;i<build.length;i++){ var opt=new Option(build[i].name,build[i].id); frag.appendChild(opt); } selectChange.appendChild(frag); selectChange.onchange=function(){ while(this.parentNode.lastChild!=this){ this.parentNode.removeChild(this.parentNode.lastChild); } var index=this.selectedIndex; if(index>0){ var cate=build[index-1]; } if(cate.children){ constructionLibrary(cate.children) } } } constructionLibrary(build); </script> </html>
红色部分代码,用递归解决多级联动,基本实现根据数据进行查找,不过递归效率是非常低的,视情况使用。