首页 > 代码库 > 省市联动

省市联动

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>省市联动</title>
</head>
<body>
<select id="province"></select>
<select id="city"></select>
<script src="http://www.mamicode.com/js/省市联动.js"></script>
</body>
</html>

javascript

 

(function() {
var data = http://www.mamicode.com/[
{
name: ‘四川省‘,
citys: [‘成都市‘, ‘绵阳市‘, ‘南充市‘]
},
{
name: ‘广东省‘,
citys: [‘广州市‘, ‘深圳市‘, ‘东莞市‘]
},
{
name: ‘河南省‘,
citys: [‘郑州市‘, ‘洛阳市‘]
},
{
name: ‘台湾省‘,
citys: [‘郑州市‘, ‘洛阳市‘]
}
];

var provinceSelect = document.getElementById(‘province‘);
var citySelect = document.getElementById(‘city‘);

// 把省份select里面的内容显示出来
for(var i = 0; i < data.length; i++) {
// 省份的名称 data[i].name
var option = document.createElement(‘option‘);
option.innerHTML = data[i].name;
// option.onclick = function() {
// showCitys(this.index);
// // console.log(123);
// };
provinceSelect.appendChild(option);
}

provinceSelect.onchange = function() {
showCitys(provinceSelect.selectedIndex);
};

// 在citySelect中,应该默认显示第一个省份的城市
showCitys(0);

// 显示城市select里面的内容
function showCitys(provinceIndex) {
// 清空citySelect里面的内容
citySelect.innerHTML = ‘‘;

for(var i = 0; i < data[provinceIndex].citys.length; i++) {
var option = document.createElement(‘option‘);
option.innerHTML = data[provinceIndex].citys[i];
citySelect.appendChild(option);
}
}

// showCitys(1);
})();

省市联动