效果图:
代码如下:
<!DOCTYPE HTML> <html> <head> <title>联动菜单</title> <meta charset="utf-8" /> </head> <body> <div id="category"></div> <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":'手套'} ]} ]; (function(arr){ var select=//创建select document.createElement("select"); //将opt追加到select中 select.add(new Option("-请选择-",-1)); //遍历arr中每个商品类别对象 for(var i=0;i<arr.length;i++){ //将option追加到select中 select.add( new Option(arr[i].name,arr[i].id) ); } var fun=arguments.callee; //为select绑定onchange事件: select.onchange=function(){ //this->.前的元素对象 //获得this的parent,保存在变量parent中 var parent=this.parentNode; //反复:只要this不是parent的最后一个子节点 while(this!=parent.lastChild){ //删除parent下的最后一个子节点 parent.removeChild(parent.lastChild); } //获得当前select选中项的下标i var i=this.selectedIndex; if(i>0){//如果i>0 //获得arr中i-1位置的商品类别对象的children,保存在变量subCate var subCate=arr[i-1].children; //调用fun(subCate) subCate!==undefined&&fun(subCate); } } //将select追加到id为category的父元素下 document.getElementById("category") .appendChild(select); })(categories); </script> </body> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!