<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<style type="text/css">
.box{
500px;
padding: 20px;
border: 1px solid #aaa;
border-radius: 3px;
margin: 100px auto;
}
.box select{
150px;
}
.box label{
margin:0 20px;
}
</style>
<script type="text/javascript">
var provs = [{"id":"01","pName":"河南省"},{"id":"02","pName":"河北省"},{"id":"03","pName":"山西省"},{"id":"04","pName":"山东省"},{"id":"05","pName":"四川省"}];
var citys = [{"id":"001","cName":"安阳市","pId":"01"},{"id":"002","cName":"郑州市","pId":"01"},{"id":"003","cName":"新乡市","pId":"01"},{"id":"004","cName":"石家庄","pId":"02"},{"id":"005","cName":"邯郸","pId":"02"},{"id":"006","cName":"大同","pId":"03"},{"id":"007","cName":"太原","pId":"03"},{"id":"008","cName":"济南","pId":"04"},{"id":"009","cName":"青岛市","pId":"04"},{"id":"010","cName":"成都","pId":"05"},{"id":"011","cName":"绵阳市","pId":"05"}];
window.onload = function(){
//1.添加省份选择
var selProv = document.getElementById('province');
for (var i = 0; i < provs.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = provs[i].pName;
// opt.innerHTML = provs[i]['pName'];
// 把省份的id写入到option的value属性中
opt.value = provs[i].id;
selProv.append(opt);
}
//2.选中省份后,动态创建出备选城市
var selCity = document.getElementById('city');
selProv.onchange = function(){
//2.0先清空城市下拉选框的选项
selCity.options.length = 1;
//2.1拿到所选省份的id
var pId = this.value;
for (var i = 0; i < citys.length; i++) {
if(citys[i].pId == pId){
var opt = document.createElement('option');
opt.innerHTML = citys[i].cName;
opt.value = citys[i].id;
selCity.append(opt);
}
}
}
}
</script>
</head>
<body>
<div class="box">
请选择:
<select id="province">
<option value="00">----请选择----</option>
</select><label for="provice">省</label>
<select id="city">
<option value="000">----请选择----</option>
</select><label for="provice">市</label>
</div>
</body>
</html>