题目:
两个select标签联动!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<select class="province" >
<option>请选择省份</option>
</select>
<select class="city" >
<option>请选择市区</option>
</select>
<script>
data={"湖南":["长沙","邵阳","郴州"],"上海":["虹口","浦东","闵行"]}
var province_ele=document.getElementsByClassName("province")[0];
var city_ele=document.getElementsByClassName("city")[0];
var province_options=province_ele.getElementsByTagName("option");
var city_options=province_ele.getElementsByTagName("option");
for (var i in data){
var o1_ele=document.createElement("option");
o1_ele.innerHTML=i;
province_ele.appendChild(o1_ele);
}
// 方案一
// province_ele.onchange=function () {
// for (var i in province_options){
// if(province_options[i].selected) {
// var province = province_options[i].innerHTML;
// city_ele.options.length = 1;
// if (province != "请选择省份") {
// var city_data = data[province];
// for (var x of city_data) {
// var o2_ele = document.createElement("option");
// o2_ele.innerHTML = x;
// city_ele.appendChild(o2_ele);
// }
// }
// }
// }
// };
//方案二
province_ele.onchange=function () {
//获取选中的select标签的下标
// console.log(this.selectedIndex);
//获取选中的select标签的innerHTML
// console.log(this.options[this.selectedIndex].innerHTML);
var province=this.options[this.selectedIndex].innerHTML;
city_ele.options.length=1;
if(province!="请选择省份"){
var city_data=data[province];
for (var x of city_data){
var city_opt=document.createElement("option");
city_opt.innerHTML=x;
city_ele.appendChild(city_opt);
}
}
}
</script>
</body>
</html>