三级联动考察的应该是对于数据的处理,只要清楚其中的关系,再多几级都是一样的:
html部分:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>3级联动菜单</title> <script> var region = { 广东: { "广州":["广州1","广州2","广州3"], "珠海":["珠海1","珠海2","珠海3"], "佛山":["佛山1"] }, 湖南: { "常德":["石门","桃源","临澧","汉寿"], "益阳":["益阳1","益阳2","益阳3"] } } </script> </head> <body> <select id="province" onchange="change(this.value);"> <option>请选择省份</option> </select> <select id="city" onchange="countyChange(this.value);"> <option>请选择地市</option> </select> <select id="county"> <option>请选择县城</option> </select> <script src='test.js'></script> </body> </html>
js部分:
var province = document.querySelector("#province"); var city = document.querySelector("#city"); var county = document.querySelector("#county"); //二级联动不用定义你选的省份,直接用省份(key)来决定下面的市(value)值 var provinceName = null; for (ele in region){ var op = new Option(ele , ele , false , false); //new Option("文本","值",true,true).后面两个true分别表示默认被选中和有效 //console.log(op); province.options[province.length] = op; } var change = function(src){ city.innerHTML = ""; if(src === '请选择省份'){ var op = new Option('请选择地市' , '请选择地市' , false , false); city.options[0] = op; }else{ for (index in region[src]){ //console.log(index); var op = new Option(index , index , false , false); city.options[city.length] = op; } } //记住选择省份的值 provinceName=src; countyChange(city.value) } var countyChange = function(src2){ county.innerHTML = ""; if(src2 === '请选择地市'){ var op = new Option('请选择县城','请选择县城', false , false); county.options[0] = op; }else{ for (index in region[provinceName][src2]){ //console.log(index); var op = new Option(region[provinceName][src2][index] , region[provinceName][src2][index] , false , false); county.options[county.length] = op; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。