需求
模拟地址选择时的下拉列表,先选择省,然后是市,最后是区
Html页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript案例:省市区选择</title>
<script src="js/provice_city_area.js"></script>
</head>
<body>
<label>省:</label>
<select name="provice" id="provice" >
<option value="">请选择省份</option>
</select>
<label>市:</label>
<select name="city" id="city">
<option value="">请选择城市</option>
</select>
<label>区:</label>
<select name="area" id="area">
<option >请选择地区</option>
</select>
<br>
<button id = "btn">重置</button>
</body>
<script src="../js/jquery-1.9.1.min.js"></script>
<script>
provice_city_area();
</script>
</html>
核心JS代码如下:provice_city_area.js
function provice_city_area() {
var total = {
"data": [{
"label": "11",
"value": "北京市",
"children": [{
"label": "1101",
"value": "市辖区",
"children": [{
"label": "110101",
"value": "东城区"
}, {
"label": "110102",
"value": "西城区"
}, {
"label": "110105",
"value": "朝阳区"
}, {
"label": "110106",
"value": "丰台区"
}]
}]
}
}
var provice = [];
var proviceSelect = document.getElementById("provice");
var proviceCity = document.getElementById("city");
var proviceCityArea = document.getElementById("area");
var button = document.getElementById("btn");
//获取省份列表
function selectProvice() {
proviceSelect.innerHTML="";
var option1 = document.createElement("option");
option1.innerText = "请选择省份";
proviceSelect.appendChild(option1);
for(var i = 0 ;i < total.data.length;i++){
var option = document.createElement("option");
option.innerText = total.data[i].value;
provice[i] = total.data[i].value;
proviceSelect.appendChild(option);
}
};
selectProvice();
//获取对应城市
proviceSelect.addEventListener("mouseleave",function selectCity() {
proviceCity.innerHTML = "<option value=\"\">请选择市区</option>";
var index = proviceSelect.selectedIndex; // 选中索引
var text = proviceSelect.options[index].text; // 选中文本
for(var i = 0 ;i < total.data.length;i++){
if(text ===total.data[i].value ){
for(var j = 0; j <total.data[i]['children'] .length;j++){
var option = document.createElement("option");
option.innerText = total.data[i]['children'][j].value;
proviceCity.appendChild(option);
}
}
}
});
//获取对应区域
proviceCity.addEventListener("mouseleave", function selectArea(){
proviceCityArea.innerHTML = "<option value=\"\">请选择地区</option>";
var index1 = proviceCity.selectedIndex; // 选中索引
var text1 = proviceCity.options[index1].text; // 选中文本
for(var i = 0 ;i < total.data.length;i++){ //遍历省集合
for(var j = 0; j <total.data[i]['children'] .length;j++){ //遍历市集合
if(text1 ==total.data[i]['children'][j].value){
for(var k = 0 ; k <total.data[i]['children'][j]['children'].length;k++ ){
var option = document.createElement("option");
option.innerText = total.data[i]['children'][j]['children'][k].value;
proviceCityArea.appendChild(option);
}
}
}
}
});
//重置
button.addEventListener("click",function () {
selectProvice();
proviceCity.innerHTML = "<option value=\"\">请选择市区</option>";
proviceCityArea.innerHTML = "<option value=\"\">请选择地区</option>";
});
}
因为省市区数据量非常大,所有此处我只放了一个城市的信息
具体数据