JS二维数组练习:省份,城市。联动的两种实现方式
第一种方式:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--onchange 当改变选择时调用的事件句柄。-->
省份:<select id="sel" onchange="sele2()">
<option value="">省份</option>
</select>
城市:<select id="sel2">
<option value="">城市</option>
</select>
<!--
var a = ["陕西","山西","内蒙","吉林"];
var b =[["西安","榆林"],["太原","晋中"],["鄂尔多斯","呼和浩特"],["长春","沈阳"]];
-->
<script type="text/javascript">
var a = ["陕西","山西","内蒙","吉林"];
var b =[["西安","榆林"],["太原","晋中"],["鄂尔多斯","呼和浩特"],["长春","沈阳"]];
//循环数组a,将内容显示到id=sel的select中
for (var i=0;i<a.length;i++) {
//创建一个<option></option>
var option = document.createElement("OPTION");
//获取到ID为sel的select元素
var select = document.getElementById("sel");
//给option指定text属性值和value的属性值
option.text = a[i];
option.value = i;
//将option添加到selete里面
select.add(option);
}
function sele2(){
//获取select对象中option的value值
//1.获得select对象
var selectNode=document.getElementById("sel");
//2.获得选中option的索引
var index=selectNode.selectedIndex;
//3.根据索引获取option的value值
var value=parseInt(selectNode.options[index].value);
var select2 = document.getElementById("sel2");
select2.options.length=1;
switch (value){
case 0:
var i=value;
for (var j=0;j<b[i].length;j++) {
var option = document.createElement("OPTION");
option.text = b[i][j];
option.value = j;
select2.add(option);
}
break;
case 1:
var i=value;
for (var j=0;j<b[i].length;j++) {
var option = document.createElement("OPTION");
option.text = b[i][j];
option.value = j;
select2.add(option);
}
break;
case 2:
var i=value;
for (var j=0;j<b[i].length;j++) {
var option = document.createElement("OPTION");
option.text = b[i][j];
option.value = j;
select2.add(option);
}
break;
case 3:
var i=value;
for (var j=0;j<b[i].length;j++) {
var option = document.createElement("OPTION");
option.text = b[i][j];
option.value = j;
select2.add(option);
}
break;
default:
break;
}
}
</script>
</body>
</html>
第二种方法:
<body>
省份:
<select id="pID" onclick="showCity()">
<option>省份</option>
<option>陕西省</option>
<option>吉林省</option>
<option>河南省</option>
</select>
城市:
<select id="cID">
<option>城市</option>
</select>
<script type="text/javascript">
function showCity(){
//定义一个二维数组,存放各个省份中的城市
var citys = [[],["西安","宝鸡","咸阳"],["长春","四平","铁岭"],["郑州","洛阳","驻马店"]];
//拿到选项的下标(选中了哪个选项)
var pNode = document.getElementById("pID");
var pIndex = pNode.selectedIndex;
var cityDatas = citys[pIndex];
//拿到城市下拉框的对象
var cityNode = document.getElementById("cID");
//让“城市”下拉框中的选项内容,每次被加载后,让其值变成1(只有一个选项/一组option),避免重复被加载
cityNode.options.length = 1;
//把读取到城市信息,添加“城市”下来框选项中
for(var i=0;i<cityDatas.length;i++){
var option01 = document.createElement("option");
option01.innerHTML = cityDatas[i];
cityNode.appendChild(option01);
}
}
</script>
</body>