js中的二级联动
程序员文章站
2022-05-01 23:13:08
...
省份市级城市联动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js省市二级联动</title>
</head>
<body>
<form name="aform" method="get" action="#">
省份:<select id="province" name="province"></select>
城市:<select id="city" name="city"></select>
</form>
</body>
</html>
<script type="text/javascript">
var provinces = ["请选择省份", "北京市", "天津市", "上海市", "重庆市", "江苏省", "浙江省", "江西省", "海南省"];
var citys = [
["请选择城市"],
["北京市"],
["天津市"],
["上海市"],
["重庆市"],
["南京市", "无锡市", "徐州市", "常州市", "苏州市", "南通市", "连云港市", "淮安市", "盐城市", "扬州市", "镇江市", "泰州市", "宿迁市"],
["杭州市", "宁波市", "温州市", "绍兴市", "湖州市", "嘉兴市", "金华市", "衢州市", "台州市", "丽水市", "舟山"],
["南昌市", "九江市", "上饶市", "抚州市", "宜春市", "吉安市", "赣州市", "景德镇", "萍乡市", "新余市", "鹰潭市"],
["海口市", "三亚市", "三沙市", "儋州市"]
];
//获取元素
var province = document.getElementById('province');
var city = document.getElementById('city');
//创建省份
for (var k in provinces) {
var option = document.createElement('option');
option.innerText = provinces[k]
province.append(option);
}
//设置市级城市默认第一个
var index = 0;
var c_option = document.createElement('option');
//给第一个option赋值
c_option.innerText = citys[index];
city.append(c_option);
//当省份城市改变的时候改变相对应的市级城市
province.onchange = function() {
city.options.length = 0;
//创建相对应的市级城市
for (var k in citys[this.selectedIndex]) {
var option = document.createElement('option');
option.innerText = citys[this.selectedIndex][k];
city.append(option);
}
}
</script>