【案例】城市地址三级联动
注意点:
1、<option value=""></option> value值的设置
2、select的onchange事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>城市地址三级联动</title>
<style>
*{
margin:0;
padding:0;
}
#pro,#city,#county{
width: 120px;
height: 30px;
margin-left: 10px;
margin-top: 20px;
}
#city,#county{
display: none;
}
</style>
<!--引入一个包含地址信息的对象的js文件-->
<script src="./location.js"></script>
</head>
<body>
<select name="" id="pro"></select>
<select name="" id="city"></select>
<select name="" id="county"></select>
</body>
<script>
//获取元素
var pro = document.getElementById('pro');
var city = document.getElementById('city');
var county = document.getElementById('county');
var proStr = '<option value="">请选择</option>';
for(var i in address[0]){
proStr += '<option value="0,'+ i +'">'+ address[0][i] +'</option>';
}
pro.innerHTML = proStr;
//省发生改变时,显示相应的市
pro.onchange = function(){
city.style.display = 'inline-block';
var cityStr = '<option value="">请选择</option>';
var index = this.value;
if(index == ''){
city.style.display = 'none';
county.style.display = 'none';
return;
}
for(var i in address[index]){
cityStr += '<option value="'+ index +','+ i +'">'+ address[index][i] +'</option>';
}
city.innerHTML = cityStr;
}
//市发生改变时,显示相应的县
city.onchange = function(){
county.style.display = 'inline-block';
var countyStr = '<option value="">请选择</option>';
var index = this.value;
if(index == ''){
county.style.display = 'none';
return;
}
for(var i in address[index]){
countyStr += '<option value="">'+ address[index][i] +'</option>';
}
county.innerHTML = countyStr;
}
</script>
</html>