<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>省市联动</title>
</head>
<body>
<select id="province" onchange="changeProvince(this.value)">
<option value="0">-- 请选择 --</option>
<option value="北京">北京</option>
<option value="重庆">重庆</option>
<option value="广东">广东</option>
</select>
<select id="city"> </select>
</body>
<script type="text/javascript">
// 获取city
var city = document.getElementById("city");
// 创建一个数组存储数据
// 二维数组
var arr = new Array(3);
arr[0] = ["北京", "中关村", "朝阳区"];
arr[1] = ["重庆", "梁平", "万州"];
arr[2] = ["广东", "广州", "东莞"];
function changeProvince(val) {
// 清空city
if (city.length > 0) {
var cities = city.getElementsByTagName("option");
for (var i = 0; i < cities.length; i++) {
city.remove(cities[i]);
i--;
}
}
for (var i = 0; i < arr.length; i++) {
var arrx = arr[i];
// 得到数组的第一个值
var province = arrx[0];
if (province == val) {
// 遍历arrx
for (var j = 1; j < arrx.length; j++) {
// 得到城市的名称
var p = arrx[j];
// 创建option
var option = document.createElement("option");
var text = document.createTextNode(p);
option.appendChild(text);
// 添加option到city
city.appendChild(option);
}
}
}
}
</script>
</html>