三级联动小案例
程序员文章站
2022-10-27 21:07:37
此小案例适合数据较少的类似三级联动的小效果,省市区三级联动参见 https://www.cnblogs.com/xiaoyaolang/p/11896484.html
此小案例适合数据较少的类似三级联动的小效果,省市区三级联动参见
<body>
<select name="" id="prov">
<option value="">请选择省</option>
</select>
<select name="" id="city">
<option value="">请选择市</option>
<option value="">请先选择省</option>
</select>
<select name="" id="county">
<option value="">请选择县</option>
<option value="">请先选择市</option>
</select>
</body>
</html>
<script src="jquery-1.8.1.min.js"></script>
<script>
var provarr = ["辽宁","山西","河北"];
// 0 1 2
var cityarr = [["沈阳","大连","铁岭"],["大同","太原"],["邯郸","石家庄","唐山","雄安"]];
// 0 1 2 0 1 0 1 2 3
var countyarr = [[["s1","s2"],["d1"],["昌图","莲花乡"]],[["t1","t2"],["y1"]],[["h1"],["s1","s2"],["tangshan1"],["xiongan1"]]];
// 00 01 02 10 11 20 21
//页面加载后 将省的数组信息 添加到页面上
for(var i = 0; i < provarr.length; i++){
$("#prov").append($("<option value="+i+">"+provarr[i]+"</option>"));
}
$("#prov").change(function(){//点击省把市添加进来
$("#city")[0].length = 1;
var index = $(this).val();//省的下标 0-1
var cityary = cityarr[index];
for(var i = 0; i < cityary.length; i++){
$("#city").append($("<option value="+index+"-"+i+">"+cityary[i]+"</option>"));
}
})
$("#city").change(function(){
$("#county")[0].length = 1;
var index = $(this).val();//0-0 0-1 0-2
var proindex = index.split("-")[0];//省的下标
var cityindex = index.split("-")[1];//城市的下标
var countyary = countyarr[proindex][cityindex];
for(var i = 0; i < countyary.length; i++){
$("#county").append($("<option>"+countyary[i]+"</option>"));
}
})
</script>