刚始学习java刚好看到用js实现省市二级联动的效果,就想着写篇博客,顺便检验下自己的学习成果。
好了废话少说先看看实际效果:
技术分析:
要实现这个功能呢,首先要用到html+js
这里用建一个下拉列表,绑定onchange事件
<select onchange="changeCity(this.value)">
<option>--请选择--</option>
<option value="0">湖北</option>
<option value="1">湖南</option>
<option value="2">河北</option>
<option value="3">河南</option>
</select>
<select id="city">
</select>
好了下面是script部分了
<script>
//1.创建一个二维数组用于存储省份和城市
var cities = new Array(3);
cities[0] = new Array("武汉市","黄冈市","襄阳市","荆州市");
cities[1] = new Array("长沙市","郴州市","株洲市","岳阳市");
cities[2] = new Array("石家庄市","邯郸市","廊坊市","保定市");
cities[3] = new Array("郑州市","洛阳市","开封市","安阳市");
function changeCity(val){
//7.获取第二个下拉列表
var c=document.getElementById("city");
//9.清空第二个下拉列表的option内容
c.options.length=0;
//2.遍历二维数组中的省份
for(var i=0;i<cities.length;i++){
//注意,比较的是角标
if(val==i){
//3.遍历用户选择的省份下的城市
for(var j=0;j<cities[i].length;j++){
//alert(cities[i][j]);
//4.创建城市的文本节点
var a = document.createTextNode(cities[i][j]);
//5.创建option元素节点
var b = document.createElement("option");
//6.将城市的文本节点添加到option元素节点
b.appendChild(a);
//8.将option元素节点添加到第二个下拉列表中去
c.appendChild(b);
}
}
}
}
</script>
这样这个简单的省市二级联动就完成了,是不是特别简单呢?本人因为偷懒所以只写了四个省市,如果想完善点可以自己添加省市哦。
小编再为大家分享一位网友分享的一段代码:原生js实现省市二级联动,再此谢谢作者的分享。
通过document.createElement()创建option选项,再遍历数组appendChild到select对象内,三级联动就是用三位数组和嵌套遍历来实现。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js省市二级联动</title>
</head>
<body>
<form name="aform" method="get" action="#">
省份:<select id="province" name="province" onchange="changeProvince(this.selectedIndex)"></select>
城市:<select id="city" name="city"></select>
</form>
</body>
</html>
<script type="text/javascript">
var provinces=["请选择省份","北京市","天津市","上海市","重庆市","江苏省","浙江省","江西省","海南省"];
var citys=[
["请选择城市"],
["北京市"],
["天津市"],
["上海市"],
["重庆市"],
["南京市","无锡市","徐州市","常州市","苏州市","南通市","连云港市","淮安市","盐城市","扬州市","镇江市","泰州市","宿迁市"],
["杭州市","宁波市","温州市","绍兴市","湖州市","嘉兴市","金华市","衢州市","台州市","丽水市","舟山"],
["南昌市","九江市","上饶市","抚州市","宜春市","吉安市","赣州市","景德镇","萍乡市","新余市","鹰潭市"],
["海口市","三亚市","三沙市","儋州市"]
];
window.onload=function(){
var province=document.getElementById("province");
var city=document.getElementById("city");
var index=0;
//创建好后加入到列表中
for(var i in provinces)
{
var option = document.createElement("option");
option.text=provinces[i];
option.value=provinces[i];
province.appendChild(option);
}
var option = document.createElement("option");
option.text=citys[index];
option.value=citys[index];
city.appendChild(option);
}
function changeProvince(selectedIndex){
var city=document.getElementById("city");
city.options.length=0;
for(var i in citys[selectedIndex])
{
var option = document.createElement("option");
option.text=citys[selectedIndex][i];
option.value=citys[selectedIndex][i];
city.appendChild(option);
}
}
</script>