JS实现三级联动
js实现三级联动
·
js实现三级联动
三级联动就是平时网页上需要选择的省市县对应位置的下拉栏模块,当选择好省位置后市的下拉栏更新为已选省的,县类似。在日常生活中我们经常使用比如各类购物软件的地址栏,各种平台的认证填写的家挺住址都会用到三级联动,本次内容为使用JS实现简单的三级联动。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
//引入jQuery cdn加速
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
//创建三个下拉框这里为了方便id定义为a、b、c
<select name="" id="a">
</select>
<select name="" id="b">
</select>
<select name="" id="c">
</select>
<script type="text/javascript">
//创建两个对象用来存储地名
var obj={
"河南":["郑州","周口","商丘","安阳","南阳"],
"云南":["大理","丽江","昆明","玉溪"],
"山东":["菏泽","青岛","济南","烟台"]
}
var obj1={
"郑州":["金水区","新郑市","二七区","中牟县"],
"周口":["鹿邑县","郸城县","21","121"],
"商丘":["1223","321","321","123"],
"安阳":["滑县","21","321"],
"南阳":["111","222","333","444"],
"大理":["AAA","BBB","CCC","DDD"],
"丽江":["EEE","FFF","GGG","HHH"],
"昆明":["III","JJJ","KKK","RRR"],
"玉溪":["MMM","NNN","XXXX"],
"菏泽":["曹县","HEHE","HAHA","HEIHEI"],
"青岛":["XIXI","LALA","CA","WC"],
"济南":["猪娃县","猪头县","猪县"],
"烟台":["猪奶子县","猪脑县","猪肘子县"]
}
//for-in循环输出obj的Key
for ( var x in obj) {
$("<option>"+x+"</option>").appendTo("#a");
}
//创建一个改变事件获取框中被选中的地名获得值
$("#a").change(function(){
var arr=$(this).val();
//获取的值为obj的key 这里将obj的值赋给arr
var arr1=obj[arr];
//清除上次点击打印出来的值
$("#b").html("");
//循环输出arr的值
for(var i=0;i<arr1.length;i++){
$("<option>"+arr1[i]+"</option>").appendTo("#b");
}
//虚拟点击
$("#b").change();
})
//基本同上不过是利用obj的值当作obj1的key获取obj1的值
$("#b").change(function(){
var arr2=$(this).val();
var arr3=obj1[arr2]
$("#c").html("");
for(var j=0;j<arr3.length;j++){
$("<option>"+arr3[j]+"</option>").appendTo("#c");
}
})
//虚拟点击点击
$("#a").change();
</script>
</body>
</html>
实现效果如下
本文章是本人的第一篇博客,由于本人是一名在学习的学生,可能写的某些地方不准确、不全面,欢迎大佬指导修正,也希望我自己学到的东西能够给一些不懂又想要学习的小白一些帮助
更多推荐
已为社区贡献1条内容
所有评论(0)