根据省份确定城市的下拉列表
- 基础的二级联动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
请输入您家乡所在的地区:
<select id="s" onchange="myFunction()">
<option value="">请选择</option>;
<option value="o1">河南</option>;
<option value="o2">河北</option>;
<option value="o3">湖南</option>;
<option value="o4">湖北</option>;
</select>
<select id="s1">
</select>
</div>
</body>
<script>
var s=document.getElementById("s");
function myFunction(){
if(s.value=="o1"){
document.getElementById("s1").innerHTML="<option>郑州</option>;<option>南阳</option>;<option>开封</option>;"
}else if(s.value=="o2"){
document.getElementById("s1").innerHTML="<option>石家庄</option>;<option>邯郸</option>;<option>唐山</option>;"
}else if(s.value=="o3"){
document.getElementById("s1").innerHTML="<option>长沙</option>;<option>邵阳</option>;<option>张家界</option>;"
}else if(s.value=="o4"){
document.getElementById("s1").innerHTML="<option>武汉</option>;<option>黄冈</option>;<option>襄阳</option>;"
}
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
请输入您家乡所在的地区:
<select id="s1">
<option value="" selected disabled>请选择</option>;
</select>
<select id="s2">
<option value="" selected disabled>请选择</option>;
</select>
</div>
</body>
<script>
var s1=document.getElementById("s1");
var s2=document.getElementById("s2");
var l=[
['河南','河北','湖南','湖北'],
['郑州','南阳','开封'],
['石家庄','邯郸','唐山'],
['长沙','邵阳','张家界'],
['武汉','黄冈','襄阳']
];
addElement(l[0],s1,"s1")
s1.onchange=function(){
var i=getIndex(l[0],s1.value);
if(i != -1){
addElement(l[i],s2,"s2")
}
}
function getIndex(arr, ele){
for(let i=0; i<arr.length; i++){
if(('s1-'+i)==ele) return i+1;
}
return -1;
}
function addElement(eles, doc, v){
doc.innerHTML = "<option value='' selected disabled>请选择</option>"; // 清空
// forEach遍历添加城市
eles.forEach((ele,index) => {
doc.innerHTML += "<option value='"+v+"-"+index+"'>"+ele+"</option>"
});
}
</script>
</html>