JavaScript结合HTML DOM实现联动菜单
Harlem 人气:0本文实例为大家分享了js三级联动菜单展示的具体代码,供大家参考,具体内容如下
效果图:
代码:
<!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":2031,"name":'九分裤'}, {"id":2031,"name":'七分裤'} ] }, ] }, {"id":30,"name":'童装',"children":[ {"id":301,"name":'帽子'}, {"id":302,"name":'套装',"children":[ {"id":3021,"name":"0-3岁"}, {"id":3021,"name":"3-6岁"}, {"id":3021,"name":"6-9岁"}, {"id":3021,"name":"9-12岁"} ]}, {"id":303,"name":'手套'} ]} ]; </script> </head> <body> <div id="category"></div> <script> //查找id为category的div保存在div中 var div=document.getElementById("category"); //定义函数createSelect,接收一个数组参数arr function createSelect(arr){ //创建一个select var sel=document.createElement("select"); //创建一个option,设置其内容为"-请选择-",值为-1,将option添加到select中 sel.add(new Option("--请选择--",-1)); //遍历arr for(var i=0;i<arr.length;i++){ //创建一个option,设置内容为当前元素的name属性,设置value为当前元素的id属性,将新option添加到select中 sel.add(new Option(arr[i].name,arr[i].id)); }//(遍历结束) //为sel绑定onchange事件 sel.onchange=function(){ //反复:只要当前select不是div的lastChild while(this!=div.lastChild) //让div删除其lastChild div.removeChild(div.lastChild); //获得当前选中项的下表-1,保存在i中 var i=this.selectedIndex-1; //如果arr中i位置的商品类别有children if(i>=0&&arr[i].children!==undefined) //用arr中i位置的商品类别的children数组创建下一个select createSelect(arr[i].children); } //将select添加到div中 div.appendChild(sel); } createSelect(categories); </script> </body> </html>
加载全部内容