效果
开始的时候
当省份这里的下拉框选择以后,城市下拉框会自动加载新的数据
源码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<select name="province" id="province">
<option value="hb">湖北</option>
<option value="hn">湖南</option>
</select>
<select name="city" id="city">
<option value="">---城市---</option>
</select>
<script>
var pro2city = {
"hb":["武汉","十堰"],
"hn":["长沙","夷陵"]
}
// 获取标签对象
var province = document.getElementById("province");
// 绑定事件
// province.onchange = function () {
province.onclick = function () {
// province.onmouseover = function () {
// 拿到选中的value值
var name = province.value;
// 找到对应的城市列表
var citys = pro2city[name];
console.log(citys);
// 把数组中的成员
// 清空选项的内容
var cityEle = document.getElementById("city"); //拿城市的选择框
cityEle.innerHTML = "";
// 添加一个东西的测试
// // 创建一个空的option标签,名字为暂时的
// var optEle = document.createElement("option");
// optEle.text = '随便占位置的';
// cityEle.append(optEle);
// 开干
// 遍历对应的城市数组
for(var i=0;i<citys.length;i++){
var optEle = document.createElement("option");
optEle.text = citys[i];
cityEle.append(optEle);
}
}
</script>
</body>
</html>
版本二
启航版
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var shenArr = new Array(); // [] shenArr = {}
shenArr["广东"] = ["广州","深圳","珠海","汕头"];
shenArr["湖南"] = ["长沙","株洲","张家界","邵阳"];
shenArr["湖北"] = ["武汉","宜昌","荆州","仙桃"];
shenArr["安徽"] = ["合肥","黄山"];
shenArr["河南"] = ["郑州","洛阳"];
console.log(shenArr)
console.log(shenArr.湖北)
function getShen() {
var s = document.getElementById("shen");
for(var v in shenArr) {
s.add(new Option(v)); //<option>广东</option>
// s.options.add(new Option(v));
}
}
function getCity(){
var s = document.getElementById("shen");
var c = document.getElementById("city");
var v = s.value; //省市名称,数组中的键
c.options.length=0;//清除city
for(var i in shenArr[v]){
c.add(new Option(shenArr[v][i]));
}
}
</script>
</head>
<body onload="getShen()">
<select id="shen" onchange="getCity()">
<option value="0">--请选择--</option>
</select>
<select id="city">--请选择--</select>
</body>
</html>