1. 程式人生 > 其它 >前端js-----三級聯動

前端js-----三級聯動

技術標籤:JavaScriptWeb前端分享一下我的心得javascriptjs前端

效果如下(原生js):

在這裡插入圖片描述------
HTML:

<body>
		請選擇省份
		<select name="" id="province">
			<option value="請選擇省份">請選擇省份</option>
		</select>
		請選擇市
		<select name="" id="cities">
			<
option
value="請選擇市">
請選擇市</option> </select> 請選擇區 <select name="" id="shiqu"> <option value="請選擇市">請選擇區</option> </select> </body>

JS:

var province = new Array();
		var cities = new Array();
		province['河北省'
] = ['石家莊', '保定', '邯鄲', '邢臺', '張家口']; province['北京市'] = ['東城', '西城', '宣武', '海淀', '崇文']; //console.log(province['河北省'][0]); cities['石家莊'] = ['裕華區','東區','西區','南區']; cities['保定'] = ['雄安新區','東區','西區','南區']; //console.log(cities['石家莊'][1]); var oProvince = document.querySelector('#province'); var
oCities = document.getElementById('cities'); var shiqu=document.getElementById('shiqu'); //console.log(typeof province['河北省']); for (var k in province) { // console.log(k); // console.log(province[k]); oProvince.add(new Option(k, k), null); } oProvince.onchange = function() { //清空市級下拉選單 oCities.length = 1; //點了河北省控制檯會獲得河北省 點了北京市會獲得北京市 //console.log(oProvince.value); var oSelect = oProvince.value; //獲取選中的省份值 for (var k in province[oSelect]) { //console.log(province[oSelect][k]); oCities.add(new Option(province[oSelect][k], province[oSelect][k]), null) } } for(var k in cities){ // console.log(k); // console.log(cities[k]); oCities.add(new Option(k,k),null); } oCities.onchange=function(){ shiqu.length = 1; //console.log(111); //console.log(oCities.value); var oSelects = oCities.value; for (var k in cities[oSelects]) { console.log(cities[oSelects][k]); shiqu.add(new Option(cities[oSelects][k], cities[oSelects][k]), null) } }