原生js二级联动(利用二维数组创建动态下拉菜单)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>利用二维数组创建动态下拉菜单</title>

</head>
<body>
<h3>请选择省份及城市</h3>
<form name="frm">
<p>省份:
<select name="optprovince" onChange="changecity()">
<option>--请选择--</option>
<option>广东</option>
<option>湖南</option>
<option>安徽</option>
</select>
</p>
<p>城市:
<select name="optcity">
<option>--请选择--</option>
</select>
</p>
</form>
<script type="text/javascript">
//创建一个二维数组
    var acity=new Array();
    acity[0]=new Array();
    acity[1]=new Array();
    acity[2]=new Array();
    acity[3]=new Array();
//给二维数组赋值
    acity[0][0]="---请选择---";
    acity[1][0]="---请选择---";
    acity[1][1]="广州市";
    acity[1][2]="深圳市";
    acity[1][3]="佛山市";
    acity[1][4]="珠海市";
    acity[1][5]="汕头市";
    acity[2][0]="---请选择---";
    acity[2][1]="长沙市";
    acity[2][2]="湘潭市";
    acity[2][3]="株洲市";
    acity[3][0]="---请选择---";
    acity[3][1]="合肥市";
    acity[3][2]="芜湖市";
    acity[3][3]="安庆市";
    function changecity()
    {
        var provinceIndex;//省份下标
        provinceIndex=document.frm.optprovince.selectedIndex;
        icitycount=0;//城市下标
        while(acity[provinceIndex][icitycount]!=null)
        icitycount++;//计算选定省份的城市个数
        document.frm.optcity.length=icitycount;//改变下拉菜单的选项数
        for(var i=0;i<icitycount;i++)//改变下拉菜单的内容
        document.frm.optcity[i]=new Option(acity[provinceIndex][i]);
        document.frm.optcity.focus();    
        console.log(document.frm.optprovince.value);//获取下拉款选项的值,一般这个值需要发送给后端
        console.log(document.frm.optcity.value);//获取下拉款选项的值,一般这个值需要发送给后端
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/sally18/article/details/84339392