<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="data.js"></script>
</head>
<body>
<select name="" id="province">
</select>
<select name="" id="city">
</select>
<select name="" id="county">
</select>
<script type="text/javascript">
// 面向过程
/*var pro = document.getElementById("province");
var city = document.getElementById("city");
var county = document.getElementById("county");
// 初始化
fillProvince();
fillCity(1);
fillCounty(1);
// 设置事件
pro.onchange = function(){
var proId = this.value;
fillCity(proId);
fillCounty(city.value);
}
city.onchange = function(){
var cityId = this.value;
fillCounty(cityId);
}
// 填充省份
function fillProvince(){
pro.innerHTML = "";
var provinces = data.provinceList;
for (var pros of provinces){
var opt = createOption(pros.ProName,pros.ProID);
pro.appendChild(opt);
}
}
// 填充市
function fillCity(proId){
city.innerHTML = "";
var cityList = data.cityList;
for (var cities of cityList){
if(cities.ProID == proId){
var opt = createOption(cities.CityName,cities.CityID);
city.appendChild(opt);
}
}
}
// 填充县
function fillCounty(cityId){
county.innerHTML = "";
var countyList = data.countyList;
for (var counties of countyList){
if(counties.CityID == cityId){
var opt = createOption(counties.DisName,counties.CountyID);
county.appendChild(opt);
}
}
}
// 创建函数封装创建option
function createOption(text,name){
var opt = document.createElement("option");
opt.innerHTML =text;
opt.value =name;
return opt;
}
*/
//面向对象
var threeLevel = {
// 初始化动作
init:function(){
//给当前对象添加属性
this.pro = document.getElementById("province");
this.city = document.getElementById("city");
this.county = document.getElementById("county");
// 默认显示
this.fillProvince();
this.fillCity(1);
this.fillCounty(1);
// 引用this对象
var self = this;
// dom事件处理程序的this指那个DOM元素
this.pro.onchange = function(){
var proId = this.value;
//函数调用对象是threeLevel,所以不能直接this,在前面赋值给self
self.fillCity(proId);
self.fillCounty(city.value);
}
this.city.onchange = function(){
var cityId = this.value;
self.fillCounty(cityId);
}
},
fillProvince: function(){
this.pro.innerHTML = "";
var provinces = data.provinceList;
for (var pros of provinces){
var opt = this.createOption(pros.ProName,pros.ProID);
this.pro.appendChild(opt);
}
},
fillCity : function(proId){
this.city.innerHTML = "";
var cityList = data.cityList;
for (var cities of cityList){
if(cities.ProID == proId){
var opt = this.createOption(cities.CityName,cities.CityID);
this.city.appendChild(opt);
}
}
},
fillCounty : function(cityId){
this.county.innerHTML = "";
var countyList = data.countyList;
for (var counties of countyList){
if(counties.CityID == cityId){
var opt =this. createOption(counties.DisName,counties.CountyID);
this.county.appendChild(opt);
}
}
},
createOption : function(text,name){
var opt = document.createElement("option");
opt.innerHTML =text;
opt.value =name;
return opt;
}
}
// 函数加载
threeLevel.init();
</script>
</body>
</html>