欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

二级联动,三级联动,初学者,纯javascript,不含jQuery

发布时间:2025/4/14 javascript 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 二级联动,三级联动,初学者,纯javascript,不含jQuery 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

二级联动:

html代码:

1 <body> 2 <select id="province" onchange="getCity(this.options.selectedIndex)"> 3 <option>请选择</option> 4 <option>广东</option> 5 <option>广西</option> 6 </select>&nbsp; 7 <select id="city"> 8 <option>请选择</option> 9 </select>&nbsp; 10 </body>

js代码:

1 var citys=[ 2 ["广州","佛山","深圳"], 3   ["柳州","桂林"] 4 ]; 5 function getCity(index){ 6 var city=document.getElementById('city'); 7 var showCity=citys[index-1]; 8 city.length=1; 9 for(var i=0;i<showCity.length;i++){ 10 city.options[i+1]=new Option(showCity[i]); 11 } 12 }

三级联动:

html代码:

1 <body> 2 <select id="province" onchange="getCity()"> 3 <option>请选择</option> 4 <option>广东</option> 5 <option>广西</option> 6 </select>&nbsp; 7 <select id="city" onchange="getArea()"> 8 <option>请选择</option> 9 </select>&nbsp; 10 <select id="area"> 11 <option>请选择</option> 12 </select>13 </body>

js代码:

1 var city = [ 2 ["广州", "朝阳", "潮州", "汕头"], 3 ["柳州", "桂林"] 4 ]; 5 var areaa = [ 6 [ 7 ["花都", "越秀", "荔湾", "天河", "海珠", "增城", "从化"], 8 ["双塔", "龙城"], 9 ["湘桥", "潮安"], 10 ["龙湖", "濠江", "朝南", "澄海"] 11 ], 12 [ 13 ["柳江", "柳南", "柳北"], 14 ["叠彩", "秀峰", "七星", "雁山", "临桂"] 15 ] 16 ]; 17 18 function getCity() { 19 var prov = document.getElementById("province"); 20 var ci = document.getElementById("city"); 21 var ar = document.getElementById('area'); 22 var provinceCity = city[prov.selectedIndex - 1]; 23 ci.length = 1; //为了处理数组切换时数据错乱 24 if(prov.selectedIndex != 0) { 25 for(var i = 0; i < provinceCity.length; i++) { 26 ci[i + 1] = new Option(provinceCity[i]); 27 //以下写法也可以 28 //ci.options[i+1]=new Option(provinceCity[i]); 29 } 30 } 31 ar.length = 1; 32 } 33 34 function getArea() { 35 var prov = document.getElementById("province"); 36 var ar = document.getElementById('area'); 37 var ci = document.getElementById("city"); 38 var provinceCityArea = areaa[prov.selectedIndex - 1][ci.selectedIndex - 1]; 39 ar.length = 1; //为了处理数组切换时数据错乱 40 if(ci.selectedIndex != 0) { 41 for(var i = 0; i < provinceCityArea.length; i++) { 42 ar[i + 1] = new Option(provinceCityArea[i]); 43 } 44 } 45 46 }

 

转载于:https://www.cnblogs.com/Meiwah/p/10565458.html

总结

以上是生活随笔为你收集整理的二级联动,三级联动,初学者,纯javascript,不含jQuery的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。