js实现 select 三级联动

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>select 三级联动</title>
</head>
<body>
	<div class="address-wrap">
        <select id="provice">
            <option>请选择省</option>
        </select>
        <select id="city">
            <option>请选择市</option>
        </select>
        <select id="county">
            <option>请选择区/县</option>
        </select>
    </div>
    <script type="text/javascript">
    var myId = function(id){
    	return document.getElementById(id);
    }
	//省份
	var arr_provice = [
		"河南省",
		"河北省",
		"江苏省"
	];
	//市区
	var arr_city = [
		["新乡市","商丘市"],
		["北京市","廊坊市"],
		["苏州市","南京市","扬州市"],
	];
	//区县
	var arr_county = [
		[
			["卫滨区","红旗区"],
			["梁园区","民权县"]
		],
		[
			["朝阳区","西城区"],
			["这个区","那个区"]
		],
		[
			["姑苏区","虎丘区","吴中区"],
			["玄武区","秦淮区","鼓楼区"],
			["广陵区","邗江区","江都区","宝应县"]
		]
	];
	//选择省份
	for (var i = 0; i < arr_provice.length; i++) {
		var myProvince = arr_provice[i];
		myId("provice").appendChild(new Option(myProvince));
	}
	//选择相应的市区
	myId("provice").onchange = function(){
		//初始化市县
		myId("city").options.length = 1;
		myId("county").options.length = 1;
		
		//使选择下拉框内容的index与数组的下标对应相等;
		pro_index = myId("provice").selectedIndex - 1;
		if (pro_index > -1) {
			//填入相应的市区
			for (var i = 0; i < arr_city[pro_index].length; i++) {
				var myCity = arr_city[pro_index][i];
				myId("city").appendChild(new Option(myCity));
			}
		}
	}
	//选择相应的区县
	myId("city").onchange = function(){
		//初始化选项
		myId("county").length = 1;

		var mar_index = myId("city").selectedIndex - 1;
		if (mar_index > -1) {
			for (var i = 0; i < arr_county[pro_index][mar_index].length; i++) {
				var myCounty = arr_county[pro_index][mar_index][i];
				myId("county").appendChild(new Option(myCounty));
			}
		}		
	}
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值