TestCode

博客园 首页 新随笔 联系 订阅 管理

动态数据之省市选择,省市的数据存储结构跟后台传过来的数据类型类似,都是Dic结构。下面是代码

1 <html xmlns="http://www.w3.org/1999/xhtml">
2 <head>
3 <title>无标题页</title>
4 <script type="text/javascript">
5 var datas = {"广东":["深圳","广州","汕头"],"福建":["福州","厦门","泉州"],"浙江":["杭州","宁波","温州"]};
6 ////////////////////////////////////////////初始化时只把省名加到第一个下拉列表中,给第一个下拉列表设定onchange事件
7 function Initial(){
8 var province = document.getElementById("province");
9 for(var data in datas){
10 var option = document.createElement("option");
11 option.value = data;
12 option.innerHTML = data;
13 province.appendChild(option);
14 }
15 province.onchange = provinceChange;
16 }
17 ////////////////////////////////////////////当选中省发生改变时触发provinceChange
18 function provinceChange(){
19 var selectItem = this.value;
20 var cities = document.getElementById("cities");
21 //////////////////////////////////////////////下面是清空原select中的内容
22 //cities.length = 0;
23 //cities.options.length = 0;
24 /*从0开始删会有删除不完全的问题
25 for(var index=0;index<cities.options.length;index++){
26 var city = cities[index];
27 cities.removeChild(city);
28 } */
29 for(var index = cities.options.length-1;index>=0;index--){
30 var city = cities[index];
31 cities.removeChild(city);
32 }
33 //////////////////////////////////////////////
34
35 if(selectItem.value == "null"){
36 return ;
37 }
38 var selectCities = datas[selectItem];
39 for(var i=0;i<selectCities.length;i++){
40 var option2 = document.createElement("option");
41 option2.value = selectCities[i];
42 option2.innerHTML = selectCities[i];
43 cities.appendChild(option2);
44 }
45
46 }
47 </script>
48 </head>
49 <body onload ="Initial()">
50 <select id="province">
51 <option value="null">请选择省</option>
52 </select>
53 <select id="cities">
54 </select>
55 </body>
56 </html>
posted on 2011-06-25 16:48  yaoguipeng  阅读(230)  评论(0编辑  收藏  举报