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":'手套'} ]} ]; function createSel(cts){//传入包含一组类别对象的数组 //创建select元素,保存在变量sel中 var sel=document.createElement("select"); //向sel添加一个新option,设置内容为"-请选择-",值为-1 sel.add(new Option("-请选择-",-1)); //遍历cts中的每个类别对象 for(var i=0;i<cts.length;i++){ //向sel中添加一个新option,设置内容为当前类别的内容,设置值为当前类别的id sel.add(new Option(cts[i].name,cts[i].id)); }//(遍历结束) //cts:[{男装,},{女装,},{童装,children:[{sub1},...] // i-1 sel.onchange=function(){//this->sel //获得当前sel选中项的下标,保存在变量i中 var i=this.selectedIndex; //获得cts中下标为i-1位置的子类型对象,保存在cate中 var cate=cts[i-1]; //反复删除category下的最后一个子节点,直到category的最后一个子节点就是当前sel时,退出循环 while(category.lastChild!=this){ category.removeChild(category.lastChild); } if(cate.children){//如果cate有children属性 //调用createSel,传入cate的children数组作为参数 createSel(cate.children); } } //将sel追加到id为category的元素中 category.appendChild(sel); } window.onload=function(){ createSel(categories); } </script> </head> <body> <div id="category"></div> </body> </html>
var data = { "province": ["广东省","山东省","西安"], "city":{ "广东省":["韶关市1","韶关市2","韶关市3","韶关市4","韶关市"], "山东省":["韶关市","韶关市","韶关市","韶关市","韶关市"], "西安":["韶关市66","韶关市77","韶关市88","韶关市99","韶关市"], } } var Pro1=''; for(var i=0;i<data.province.length;i++){ Pro1+='<option value="">'+data.province[i]+'</option>'; } $("#province").on('change',function(){ var oCity=document.getElementById('city'); oCity.innerHTML='<option>市</option>'; var City1=''; var City2=$('#province').children('option:selected').text(); for(var city_1 in data.city){ if(City2==city_1){ for(var i=0;i<data.city[city_1].length;i++){ City1+='<option value="">'+ data.city[city_1][i] +'</option>'; } $('#city').append(City1); } } }) $('#province').append(Pro1);