<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
body {
margin: 8px;
}
select {
padding: 5px;
border-radius: 5px;
}
</style>
<body>
<select>
<option value="">请选择省份</option>
</select>
<select>
<option value="">请选择市区</option>
</select>
<select>
<option value="">请选择区域</option>
</select>
<!-- 链接已封装好的ajax -->
<script type="text/javascript" src="ajaxfengzhuang.js"></script>
<script type="text/javascript">
// 1.把数据拿过来,将省份填进去
// 2.通过.onchange获取当前选中的省,市。
// 3.省,市,区
获得省:将所有数据遍历一遍,获取省objData[i].name
获取市:将所有数据都遍历一遍,将选中的省与所有数据中的省匹配,如相同,并获取当前省的市,并将市全部遍历赋值给新创建的option,再append给select[1]
获取区: 将上一步获取到的所有市都遍历一遍,如与选中的市匹配,获取当前市的所有区,并将区全部遍历赋值给新创建的option,在append给select[2]
var select = document.querySelectorAll('select');
var objData;
var city;
$.ajax({
type : 'get',
url : 'demo.php',
success : function(data) {
objData = JSON.parse(data);
for(var i = 0; i < objData.length; i++) {
var province = objData[i].name;
var option = document.createElement('option');
option.value = province;
option.innerHTML = province;
select[0].appendChild(option);
}
}
});
// change当表单里面的值发生改变的时候,并且失去焦点的时候触发
select[0].onchange = function () {
// 重置掉 市区 和区域
select[1].innerHTML = '<option>请选择市区</option>';
select[2].innerHTML = '<option>请选择区域</option>';
var curPro = this.value;
for(var i = 0; i < objData.length; i++) {
if(curPro == objData[i].name) {
city = objData[i].city;
for(var j = 0; j < city.length; j++) {
var curCity = city[j].name;
var option = document.createElement('option');
option.value = curCity;
option.innerHTML = curCity;
select[1].appendChild(option);
}
}
}
}
select[1].onchange = function () {
select[2].innerHTML = '<option>请选择区域</option>';
var curCitys = this.value;
for(var i = 0; i < city.length; i++) {
if(curCitys == city[i].name) {
var area = city[i].area;
for(var j = 0; j < area.length; j++) {
var option = document.createElement('option');
option.value = area[j];
option.innerHTML = area[j];
select[2].appendChild(option);
}
}
}
}
</script>
</body>
</html>
网友评论