<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > |
<html> |
<head> |
<title>二级联动效果</title> |
<script type= "text/javascript" > |
function changePro(){ |
//定义数据,用来存放所有的市或者区 |
var arr = [ |
[ "---选择市--" ], |
[ "海淀区" , "丰台区" , "石景山区" , "朝阳区" ], |
[ "闵行区" , "徐汇区" , "长宁区" , "松江区" , "浦东新区" , "嘉定区" ], |
[ "西安市" , "宝鸡市" , "延安市" , "榆林市" , "咸阳市" ] |
]; |
//通过id获取省的下拉框中选中的省份 |
var pS = document.getElementById( "province" ); |
//获取被选中的option的索引 |
var index = pS.selectedIndex; |
//从arr数组中获取当前选中的省对应的市数组 |
var cities = arr[index]; |
//获取到市的select对象 |
var city = document.getElementById( "city" ); |
//在省改变的情况下,需要清空市中的原有数据 |
city.options.length = 1; |
|
|
//遍历市的这个数组,然后动态的创建option标签对象,并把这个对象添加到id为city的这个select中 |
for ( var i=0;i<cities.length;i++){ |
//创建option对象 |
var option = document.createElement( "option" ); |
//给option添加文本元素 |
option.innerHTML = cities[i]; |
//把option对象添加到市的这个select中 |
city.appendChild(option); |
} |
} |
|
|
</script> |
</head> |
<body> |
<select id= "province" onchange= "changePro()" > |
<option>---选择省---</option> |
<option>北京市</option> |
<option>上海市</option> |
<option>陕西省</option> |
</select> |
|
|
<select id= "city" > |
<option>---选择市---</option> |
|
</select> |
|
|
|
</body> |
</html> |