未实现任何功能之前:
实现功能之后:
实现该功能的jQuery核心代码:
<script>
var provinceArr=new Array(5);
provinceArr[0]=new Array("南安市","泉州市","厦门市","福安市","福州市");
provinceArr[1]=new Array("郑州市","洛阳市","濮阳市","驻马店市");
provinceArr[2]=new Array("石家庄市","唐山","秦皇岛","邯郸");
provinceArr[3]=new Array("西安市","宝鸡市","延安");
provinceArr[4]=new Array("菏泽市","济南市","青岛"); $(function(){
$("#province").change(function(){ $("#city").empty();//清空
var provinceID=this.value;
if(provinceID==-1){
$("#city").html("<option value=\"-1\">--请选择--</option>");
}else{
for(var i=0;i<provinceArr[provinceID].length;i++){
var ption=document.createElement("option");//创建节点
console.log(ption);
ption.innerText=provinceArr[provinceID][i];
$("#city").append(ption);
}
}
}); })
</script>
实现该二级省市联动的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery实现省市联动</title>
<script src="js/jquery-3.3.1.js"></script>
<script>
var provinceArr=new Array(5);
provinceArr[0]=new Array("南安市","泉州市","厦门市","福安市","福州市");
provinceArr[1]=new Array("郑州市","洛阳市","濮阳市","驻马店市");
provinceArr[2]=new Array("石家庄市","唐山","秦皇岛","邯郸");
provinceArr[3]=new Array("西安市","宝鸡市","延安");
provinceArr[4]=new Array("菏泽市","济南市","青岛"); $(function(){
$("#province").change(function(){ $("#city").empty();//清空
var provinceID=this.value;
if(provinceID==-1){
$("#city").html("<option value=\"-1\">--请选择--</option>");
}else{
for(var i=0;i<provinceArr[provinceID].length;i++){
var ption=document.createElement("option");//创建节点
console.log(ption);
ption.innerText=provinceArr[provinceID][i];
$("#city").append(ption);
}
}
}); })
</script>
</head>
<body>
<select id="province">
<!--显示省份-->
<option value="-1">--请选择--</option>
<option value="0">福建省</option>
<option value="1"> 河南省</option>
<option value="2">河北省</option>
<option value="3">陕西省</option>
<option value="4">山东省</option> </select>
<select id="city">
<!--显示市-->
<option value="-1">--请选择--</option>
</select>
</body>
</html>
jQuery实现省市联动.html
当选择另一个省份时,把现有的城市清空,将更新为所选省份的的城市
$("#city").empty();//清空
创建节点是为了使省份的城市在option中显示
var ption=document.createElement("option");//创建节点
ption.innerText=provinceArr[provinceID][i];
$("#city").append(ption);