城市选择下拉菜单三级联动

时间:2023-02-13 17:08:40
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>城市三级联动</title>
<link rel="stylesheet" type="text/css" href="city.css">
</head>
<body>
<form method="post" action="">
<select id="pro">
<option>--请选择省--</option>
</select>
<select id="city" disabled>
<option>--请选择市--</option>
</select>
<select id="district" disabled>
<option>--请选择区(县)--</option>
</select>
</form>
</body>
<script type="text/javascript" src="city.js"></script>
</html>


JavaScript
var pro = document.getElementById("pro");
var city = document.getElementById("city");
var district = document.getElementById("district");

function CityItem() {
this.items = {};
this.add = function(key, val) {
this.items[key] = val;
}
}
var cityItem = new CityItem();

cityItem.add(0, ["湖北", "陕西", "贵州"]);

cityItem.add(1, ["武汉", "襄阳", "宜昌"]);
cityItem.add(2, ["西安", "咸阳", "榆林"]);
cityItem.add(3, ["贵阳", "黔南", "黔东南"]);

cityItem.add("1_1", ["江岸", "汉阳", "洪山"]);
cityItem.add("1_2", ["襄城", "樊城", "枣阳"]);
cityItem.add("1_3", ["夷陵", "西陵", "秭归"]);

cityItem.add("2_1", ["碑林", "雁塔", "莲湖"]);
cityItem.add("2_2", ["秦都", "兴平", "武功"]);
cityItem.add("2_3", ["榆阳", "神木", "府谷"]);

cityItem.add("3_1", ["云岩", "南明", "白云"]);
cityItem.add("3_2", ["都匀", "平塘", "翁安"]);
cityItem.add("3_3", ["凯里", "榕江", "三穗"]);

for(var i in cityItem.items[0]) {
var opt = document.createElement("option");
opt.innerText = cityItem.items[0][i];
pro.appendChild(opt);
}

pro.onchange = function() {
//如果选择"--请选择省--" 选择市的下拉列表不能选择 否则可以选择
city.disabled = (this.selectedIndex < 1);
//选择区县的下拉列表不能选择
district.disabled = true;

//清空选择市和选择区县的下拉列表
city.innerHTML = "<option>--请选择市--</option>";
district.innerHTML = "<option>--请选择区(县)--</option>";

var key = this.selectedIndex;
for(var i in cityItem.items[key]) {
var opt = document.createElement("option");
opt.innerText = cityItem.items[key][i];
city.appendChild(opt);
}
}

city.onchange = function() {
//如果选择"--请选择市--" 选择区县的下拉列表不能选择 否则可以选择
district.disabled = (this.selectedIndex < 1);
//清空选择区县的下拉列表
district.innerHTML = "<option>--请选择区(县)--</option>";

var key = pro.selectedIndex + "_" + this.selectedIndex;
for(var i in cityItem.items[key]) {
var opt = document.createElement("option");
opt.innerText = cityItem.items[key][i];
district.appendChild(opt);
}
}


CSS
select{
outline: none;
}