<style type="text/css">
body{
margin:10;
padding:0;
font-size:12px;
}
</style>
<script src="js/select.js">
</script>
</head>
<body>
<form action="" method="post" name="myform">
<select id="selProvince" onchange="changeCity('selProvince','selCity')">
<script type="text/javascript">
/*调用函数自动添加省份选项,产生如下HTML代码的效果*/
fillProvince("selProvince");
</script>
<!--
<option value="00">-选择省份-</option>
<option value="01">北京市</option>
<option value="02">湖北省</option>
<option value="03">四川省</option>
......
-->
</select>
<select id="selCity">
<option value="0000" selected="selected">--选择城市--</option>
</select>
</form>
</body>
// JavaScript Document
/*使用二维数组存放省份(一维数组套一维数组来模拟),前2位表示省份编号,城市依靠此编号建立关联,类似数据库的主外键*/
var provinces=new Array(
new Array("00","--选择省份--"),
new Array("01","北京市"),
new Array("02","湖北省"),
new Array("03","四川省"),
new Array("04","江苏省"),
new Array("05","湖南省")
//按此添加其他省份,超过9用两位表示,如:"10","11"
);
/*使用二维数组存放城市,和省份的关联依靠前2位的省份编号*/
var citys=new Array(
new Array("0101","北京"), //直辖市特殊,下属只有对应的直辖市
new Array("0201","武汉"),
new Array("0202","荆州"), //同理添加湖北省的其他城市,其他省份同理 new Array("0301","成都"),
new Array("0302","绵阳"),
new Array("0401","南京"),
new Array("0401","苏州"),
new Array("0501","长沙"),
new Array("0502","株洲")
//按此添加其他省份下属城市
);
function fillProvince(provinceID){
var selProvince=document.getElementById(provinceID);
/*添加省份,下面使用的是针对下拉框对象的new和add方法和,对于普通元素则需要使用createElement和appendChild方法*/
for(var i=0;i<provinces.length;i++){
var option=new Option(provinces[i][1],provinces[i][0]);
selProvince.add(option,null);
}
selProvince.options[0].selected=true; //设置默认选项:-选择省份-
}
function changeCity(provinceID,cityID){
var selCity=document.getElementById(cityID);
selCity.options.length=0;//清空原来的所有选项
selCity.add(new Option('-选择城市-','0000'),null);
var selProvince=document.getElementById(provinceID);
var provinceCode=selProvince.options[selProvince.selectedIndex].value;
/*添加城市,条件是和对应省份关联的城市,同理,下列代码可以使用createElement和appendChild方法代替*/
for(var i=0;i<citys.length;i++){
if(citys[i][0].substring(0,2)==provinceCode){
var optionAdded=new Option(citys[i][1],citys[i][0]);
selCity.add(optionAdded,null);
}
}
selCity.options[0].selected=true; //设置默认选项:-选择城市-
}