上周末作业
拷贝的大佬的代码
大概要写成这个样子,没有做css
选择不同省份时,自动显示不同市区
HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script src="./js/city.js"></script>
</head>
<body>
<form action="#" method="get">
<select name="province" id="province" onfocus="add1()" onchange="add2()">
<option value="0">选择省份</option>
</select> 省
<select name="city" id="city" onfocus="add2()" onchange="add3()">
<option value="0">选择城市</option>
</select> 市/区
<select name="county" id="county">
<option value="0">选择地方</option>
</select> 县/区
</form>
</body>
<script>
var pro = document.getElementById('province');
var cit = document.getElementById('city');
var county = document.getElementById('county');
function add1(){
pro.length = arr.length+1;
for(var i=1;i<pro.length;i++){
pro[i].innerHTML=arr[i-1].name;
pro[i].value=i;
}
}
function add2(){
if(pro.length == 1){
return;
}
cit.value=0;
var cityList=arr[pro.value-1].city;
cit.length=cityList.length+1;
for(var i=1;i<cit.length;i++){
cit[i].innerText=cityList[i-1].name;
cit[i].value=i;
}
}
function add3(){
var countyList = arr[pro.value-1].city[city.value-1].districtAndCounty;
console.log(countyList)
county.length = countyList.length+1;
for(var i=1;i<county.length;i++){
county[i].innerText=countyList[i-1];
county[i].value=i;
}
}
</script>
</html>
这里连接了外部js文件,文件比较大,放一部分在上面,可以复制到内联js文件里。
var arr=[
{
"name": "北京市",
"city": [
{
"name": "北京市",
"districtAndCounty": ["东城区", "西城区", "崇文区", "宣武区", "朝阳区", "丰台区", "石景山区", "海淀区", "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "怀柔区", "平谷区", "密云县", "延庆县", "延庆镇"]
}
]
},
{
"name": "天津市",
"city": [
{
"name": "天津市",
"districtAndCounty": ["和平区", "河东区", "河西区", "南开区", "河北区", "红桥区", "塘沽区", "汉沽区", "大港区", "东丽区", "西青区", "津南区", "北辰区", "武清区", "宝坻区", "蓟县", "宁河县", "芦台镇", "静海县", "静海镇"]
}
]
},
{
"name": "上海市",
"city": [
{
"name": "上海市",
"districtAndCounty": ["黄浦区", "卢湾区", "徐汇区", "长宁区", "静安区", "普陀区", "闸北区", "虹口区", "杨浦区", "闵行区", "宝山区?", "嘉定区", "浦东新区", "金山区", "松江区", "青浦区", "南汇区", "奉贤区", "崇明县", "城桥镇"]
}
]
}