yingleiming

告诫自己即使再累,也不要忘记学习。成功没有捷径可走,只有一步接着一步走下去!

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

联动菜单

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>联动菜单</title>
 6 </head>
 7 <body>
 8     <div id="category"></div>
 9     <script>
10 //        使用HTML DOM的方式实现联动菜单
11         var categories=[
12             {"id":10,"name":"男装","children":[
13                 {"id":101,"name":"正装"},
14                 {"id":102,"name":"T恤衫"},
15                 {"id":103,"name":"裤衩"}
16             ]},
17             {"id":20,"name":"女装","children":[
18                 {"id":201,"name":"短裙"},
19                 {"id":202,"name":"连衣裙"},
20                 {"id":203,"name":"裤子","children":[
21                     {"id":2031,"name":"长裤"},
22                     {"id":2032,"name":"九分裤"},
23                     {"id":2303,"name":"七分裤"}
24                 ]}
25             ]},
26             {"id":30,"name":"童装","children":[
27                 {"id":301,"name":"帽子"},
28                 {"id":302,"name":"套装","children":[
29                     {"id":3021,"name":"0-3岁"},
30                     {"id":3021,"name":"3-6岁"},
31                     {"id":3021,"name":"6-9岁"},
32                     {"id":3021,"name":"9-12岁"}
33                 ]},
34                 {"id":303,"name":"手套"}
35             ]}
36         ];
37         function  createSel(cts) {//传入一个包含一组类别对象的数组
38 //            创建select元素,保存在变量sel中
39             var sel=document.createElement("select");
40 //            向sel添加一个新option,设置内容为"-请选择-",值为-1
41             sel.appendChild(new Option("-请选择-","-1"));
42 //            遍历cts中每个类别对象
43             for(var i=0;i<cts.length;i++){
44 //                向sel中添加一个新option,设置内容为当前类别的内容,设置值为当前类别的id
45                 sel.add(new Option(cts[i].name,cts[i].id));
46             }//遍历结束
47             sel.onchange=function () {//this-->sel
48 //                获得当前sel选项中的下标,保存在变量i中
49                 var i=this.selectedIndex;
50 //                获得cts中下标为i-1位置的子类型对象,保存在cate中
51                 var cate=cts[i-1];
52 //                反复删除category下最后一个子节点,直到category的最后一个子节点就是当前sel时,退出循环
53                 while (category.lastChild!=this){
54                     category.removeChild(category.lastChild);
55                 }
56                 if (cate.children){//如果cate有children属性
57                     //调用createSel,传入cate的children数组作为参数
58                     createSel(cate.children);
59                 }
60                 //将sel追加到id为category的元素中
61                 category.appendChild(sel);
62             }
63         }
64         window.onload=function () {
65             createSel(categories);
66         }
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80     </script>
81 
82 
83 
84 
85 </body>
86 </html>

 

posted on 2017-11-14 17:58  yingleiming  阅读(93)  评论(0)    收藏  举报