<html>
<head>
<script>
var city=["请选择","北京","深圳","长沙","上海"];
var cityN=[
[],
["北京1","北京2","北京3","北京4"],
["深圳1","深圳2","深圳3","深圳4"],
["长沙1","长沙2","长沙3","长沙4"],
["上海1","上海2","上海3","上海4"]
]
window.onload=function(){
createCity1();
document.getElementById('city1').onchange=selectedCity;
}
/* Option就是创建option标签,它有两个参数,第一个为val,第二个为text内容 */
/* options就是所有的option标签,而add()是select特有的方法,其中只能放option的实例 */
function createCity1(){
var city1=document.getElementById('city1');
for(var i=0;i<city.length;i++){
var op=new Option(city[i],i);
city1.options.add(op)
}
}
/*selectedIndex 为selected元素特有的属性,返回的是下拉的下标*/
function selectedCity(){
/*city1改变时,选择的城市下标*/
var index=document.getElementById('city1').selectedIndex;
var city2=document.getElementById('city2');
city2.options.length=0;
/*遍历选择的对应城市数组*/
for(var i in cityN[index]){
var op=new Option(cityN[index][i],cityN[index][i]);
city2.options.add(op);
}
}
</script>
</head>
<body>
<select id="city1">
</select>
<select id="city2"></select>
</body>
</html>
结果如图所示: