时间:2021-07-01 10:21:17 帮助过:34人阅读
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>利用二维数组创建动态下拉菜单</title> <script type="text/javascript"> //定义一个二维数组aCity,用于存储城市名称 var aCity=new Array(); aCity[0]=new Array(); aCity[1]=new Array(); aCity[2]=new Array(); aCity[3]=new Array(); aCity[4]=new Array(); aCity[5]=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[2][4]="宝安区"; aCity[2][5]="龙岗区"; aCity[2][6]="盐田区"; aCity[3][0]="--请选择--"; aCity[3][1]="越秀区"; aCity[3][2]="东山区"; aCity[3][3]="海珠区"; aCity[3][4]="荔湾区"; aCity[3][5]="天河区"; aCity[3][6]="白云区"; aCity[4][0]="--请选择--"; aCity[4][1]="西湖区"; aCity[4][2]="上城区"; aCity[4][3]="下城区"; aCity[4][4]="江干区"; aCity[4][5]="拱墅区"; aCity[4][6]="滨江区"; aCity[5][0]="--请选择--"; aCity[5][1]="新城区"; aCity[5][2]="碑林区"; aCity[5][3]="莲湖区"; aCity[5][4]="雁塔区"; aCity[5][5]="灞桥区"; aCity[5][6]="长安区"; aCity[5][7]="周至县"; function ChangeCity(){ var i,iProvinceIndex; iProvinceIndex=document.frm.optProvince.selectedIndex; iCityCount=0; while(aCity[iProvinceIndex][iCityCount]!=null) iCityCount++; //计算选定省份的城市个数 document.frm.optCity.length=iCityCount; //改变下拉菜单的选项数 for(i = 0;i<=iCityCount-1;i++) //改变下拉菜单的内容 document.frm.optCity[i]=new Option(aCity[iProvinceIndex][i]); document.frm.optCity.focus(); } </script></head><body onfocus="ChangeCity()"> <h3>选择省份及城市</h3> <form name="frm"> <p>省份: <select name="optProvince" size="1" onchange="ChangeCity()"> <option>--请选择--</option> <option>北京市</option> <option>深圳市</option> <option>广州市</option> <option>杭州市</option> <option>西安市</option> </select> </p> <p>城市: <select name="optCity" size="1"> <option>--请选择--</option> </select> </p> </form></body></html>
以上就是如何使用JavaScript实现创建动态下拉菜单效果的详细内容,更多请关注Gxl网其它相关文章!