第十二章 三级联动
2021-05-17 本文已影响0人
扶光_
<body>
<select name="" id="">
<option value="">--请选择--</option>
</select>
<select name="" id="">
<option value="">--请选择--</option>
</select>
<select name="" id="">
<option value="">--请选择--</option>
</select>
<script>
var one = document.getElementsByTagName("select")[0];
var two = document.getElementsByTagName("select")[1];
var three = document.getElementsByTagName("select")[2];
//封装添加内容 参数 因为添加的东西是不一样的
var sheng = ["辽宁","吉林","黑龙江"];
var shi = [
["沈阳市","铁岭市","大连"],
["广州市","佛山市","珠海市"],
["石家庄市","廊坊市","承德市"]
];
var xian = [
[
["大东区","沈河区","沈北区"],
["调兵山市","西丰县","昌图县"],
["中山区","沙河口区","甘井子区"]
],
[
["天河区","白云区","番禺区","越秀区","黄埔区"],
["南海区","顺德区","三水区"],
["香洲区","斗门区"]
],
[
["长安区","桥西区","新华区","藁城区"],
["安次区","广阳区","固安县"],
["双桥区","承德县","兴隆县"]
]
];
function fn(arr,element){
//arr代表数组 ,element代表添加的位置
for(var i = 0;i<arr.length; i++){
//arr[i]是数组的每一个数据
var op = document.createElement("option");
op.innerHTML = arr[i];
//同时添加value值
op.value = i;
element.appendChild(op);
}
}
//直接调用
fn(sheng,one);
//开始二级联动
var twoarr;
one.onchange = function(){
two.length = 1;
three.length = 1
//跟二级联动一样 需要用到this.value
fn(shi[this.value],two)
twoarr = xian[this.value]//进行一个拆分 拆分一个为二维数组
}
//三级联动
two.onchange = function(){
twoarr.length = 1;
fn(twoarr[this.value],three)
}
</script>