<!DOCTYPE HTML> <html> <head> <title>联动菜单</title> <meta charset="utf-8" /> <script> /*使用 HTML DOM 的方式实现联动菜单*/ var categories=[ {"id":10,"name":'男装',"children":[ {"id":101,"name":'正装'}, {"id":102,"name":'T恤'}, {"id":103,"name":'裤衩'} ]}, {"id":20,"name":'女装',"children":[ {"id":201,"name":'短裙'}, {"id":202,"name":'连衣裙'}, {"id":203,"name":'裤子',"children":[ {"id":2031,"name":'长裤'}, {"id":2032,"name":'九分裤'}, {"id":2033,"name":'七分裤'} ]}, ]}, {"id":30,"name":'童装',"children":[ {"id":301,"name":'帽子'}, {"id":302,"name":'套装',"children":[ {"id":3021,"name":"0-3岁"}, {"id":3022,"name":"3-6岁"}, {"id":3023,"name":"6-9岁"}, {"id":3024,"name":"9-12岁"} ]}, {"id":303,"name":'手套'} ]} ]; //专门遍历一级分类,创建select function loadData(data){//保存了当前同级分类的数组 //创建一个select对象 var select=document.createElement("select"); select.add(new Option("--请选择--")) //遍历data数组对象 for(var i=0;i<data.length;i++){ //创建一个option来存储遍历data中的数据 select.add(new Option(data[i].name,data[i].id)) } //将代码片段追加到id为category的节点之中 document.querySelector("#category").appendChild(select); //当选择了option之后动态添加之后的子节点select select.onchange=function(){ while(this.parentNode.lastChild!=this){//此处为什么要用while没有想清楚,后面想清楚了,因为需要去除所有的lastChild this.parentNode.removeChild(this.parentNode.lastChild); } if(data[this.selectedIndex-1].children){ loadData(data[this.selectedIndex-1].children); } } } window.onload=function(){ loadData(categories); } </script> </head> <body> <div id="category"></div> </body> </html>
多级联动菜单
最新推荐文章于 2024-04-01 14:56:45 发布