级联菜单
第一种case判断省份,添加
html:
<body>
<form action="" method="post" name="myForm">
<select id="selProvince" onchange="changeCity()">
<option>--选择省份--</option>
<option value="河南省">河南省</option>
<option value="河北省">河北省</option>
<option value="山东省">山东省</option>
<option value="四川省">四川省</option>
</select>
<select id="selCity">
<option>--选择城市--</option>
</select>
</form>
</body>
script:
function changeCity(){
var province=document.getElementById("selProvince").value;
var city=document.getElementById("selCity");
city.options.length=0;
switch(province){
case "河南省":
city.add(new Option("郑州市","郑州市"),null);
city.add(new Option("洛阳市","洛阳市"),null);
break;
case "河北省":
city.add(new Option("邯郸","邯郸市"),null);
city.add(new Option("石家庄","石家庄"),null);
break;
case "山东省":
city.add(new Option("青岛市","青岛市"),null);
city.add(new Option("烟台市","烟台市"),null);
break;
case "四川省":
city.add(new Option("成都市","成都市"),null);
city.add(new Option("乐山市","乐山市"),null);
break;
}
}
第二种方法,更优化的写法;
<form>
<tr>
<td class="left">现居住地:</td>
<td> <select id="selProvince" onchange="changeCity( )" style="width:100px">
<option>--选择省份--</option>
</select>
<select id="selCity" style="width:100px">
<option>--选择城市--</option></select></td>
</tr>
</form>
script:
<script type="text/javascript">
var cityList=new Array();
cityList['北京市']=['北京市','朝阳区','海淀区'];
cityList['四川省']=['成都市','攀枝花','乐山市'];
cityList['广东省']=['东莞市','广州','茂名市'];
function changeCity() {
var selProvince=document.getElementById('selProvince').value;
var selCity=document.getElementById('selCity');
selCity.options.length=0;
//遍历数组
for(var i in cityList){
if(i==selProvince){
//遍历数组中的值,添加给城市数组中
for(var j in cityList[i]){
selCity.add(new Option(cityList[i][j],cityList[i][j],null))
}
}
}
}
function allCity(){
var province=document.getElementById('selProvince');
for(var i in cityList){
province.add(new Option(i,i),null);
}
}
window.onload=allCity;
</script>