代码改变世界

58.省市联动-json

2017-07-06 14:23  笨笨03  阅读(166)  评论(0编辑  收藏  举报
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>省市联动-json数据</title>
 6 
 7 </head>
 8 <body>
 9 <select name="" id="province" onchange="setCity()">
10     <option value="">选择省</option>
11 </select>
12 <select name="" id="city">
13     <option value="">选择市</option>
14 </select>
15 
16 <script>
17     var proJSON = {"1": "广东省", "2": "湖北省"};
18     var cityJSON = {
19         "1": {"020": "广州", "0755": "深圳", "0756": "珠海"},
20         "2": {"027": "武汉", "0710": "襄樊", "0715": "赤壁"}
21     };
22     window.onload = function () {
23         var province = document.getElementById('province');
24         for (temp in proJSON) {
25             province.add(new Option(proJSON[temp], temp));
26 
27         }
28     };
29     function setCity() {
30         //触发了这个事件,就把二级菜单还原
31         var city = document.getElementById('city');
32         city.options.length = 1;
33         var val = document.getElementById('province').value;
34         if (!cityJSON[val])  return;
35         var sonJSON = cityJSON[val];
36         for (temp in sonJSON) {
37             city.add(new Option(sonJSON[temp], temp));
38         }
39     }
40 
41 </script>
42 </body>
43 
44 </html>
View Code
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>省市联动-json数据</title>

</head>
<body>
<select name="" id="province" onchange="setCity()">
<option value="">选择省</option>
</select>
<select name="" id="city">
<option value="">选择市</option>
</select>

<script>
var proJSON = {"1": "广东省", "2": "湖北省"};
var cityJSON = {
"1": {"020": "广州", "0755": "深圳", "0756": "珠海"},
"2": {"027": "武汉", "0710": "襄樊", "0715": "赤壁"}
};
window.onload = function () {
var province = document.getElementById('province');
for (temp in proJSON) {
province.add(new Option(proJSON[temp], temp));

}
};
function setCity() {
//触发了这个事件,就把二级菜单还原
var city = document.getElementById('city');
city.options.length = 1;
var val = document.getElementById('province').value;
if (!cityJSON[val]) return;
var sonJSON = cityJSON[val];
for (temp in sonJSON) {
city.add(new Option(sonJSON[temp], temp));
}
}

</script>
</body>

</html>