select省级联动效果
select1
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>select联动</title>
</head>
<body>
<select id="province">
<option>请选择省份:</option>
</select>
<select id="city">
<option>请选择城市:</option>
</select>
<script>
data = {"北京": ["朝阳区", "海淀区","东城区","西城区","丰台区","昌平区","通州区"],
"河北": ["石家庄", "保定市","唐山市","衡水市","秦皇岛市","涿州市"],
"山东": ["济南市","青岛市","威海市", "烟台市"]};
var province = document.getElementById("province");
var city = document.getElementById("city");
for (var i in data) {
var optionP = document.createElement("option");
optionP.innerHTML = i;
province.appendChild(optionP);
};
province.onchange = function () {
var pro = (this.options[this.selectedIndex]).innerHTML;
var citys = data[pro];
// 清空option
city.innerHTML = "";
for (var i=0;i<citys.length;i++) {
var option_city = document.createElement("option");
option_city.innerHTML = citys[i];
city.appendChild(option_city);
};
};
</script>
</body>
</html>
select2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<select name="" id="d1">
<option value="">---请选择---</option>
</select>
<select name="" id="d2">
<option value="">---请选择---</option>
</select>
<script>
var data = {"河北省": ["廊坊", "邯郸"],
"北京": ["朝阳区", "海淀区"],
"山东": ["威海市", "烟台市"],
"上海": ["静安区","黄浦区"],
"深圳": ["南山区","龙岗区"]
};
var seEle = document.getElementById('d1');
var se2Ele = document.getElementById('d2');
for (var i in data){
// 创建option标签
var optEle = document.createElement('option');
// 给标签添加内部文本值
optEle.innerText = i;
// 给标签设置value属性值
optEle.value = i;
// 将创建好的option标签添加到第一个select框中
seEle.appendChild(optEle)
}
// 给第一个select框绑定change事件
seEle.onchange = function () {
var currentPro = seEle.value;
var currentCityList = data[currentPro];
// 先清空第二个select框中所有的option标签
se2Ele.innerHTML = '';
var opttEle = document.createElement('option');
opttEle.innerText = '---请选择---';
se2Ele.appendChild(opttEle);
// 循环遍历数组
for (let i=0;i<currentCityList.length;i++){
// 动态创建标签
var optEle = document.createElement('option');
optEle.innerText = currentCityList[i];
optEle.value = currentCityList[i];
// 将创建出来的option标签添加到第二个select框中
se2Ele.appendChild(optEle)
}
}
</script>
</body>
</html>