-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
106 lines (92 loc) · 2.5 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<!DOCTYPE html>
<html>
<head>
<title>原生js 三级联动</title>
<meta charset="utf-8">
<body>
省<select id='province' onchange="changeProvince()"></select>
市<select id='city' onchange="changeCity()"></select>
区<select id='area'></select>
<script type="text/javascript">
var arr = [
{'name' : '四川', 'child': [
{
'name': '广安','child': [{'name': '邻水'},{'name': '子中'}]
},
{
'name': '广元','child': [{'name': '水灵'},{'name': '浪子'}]
}
]
},
{'name' : '重庆', 'child': [
{
'name': '重庆','child': [{'name': '江北'},{'name': '渝北'},{'name': '大渡口'}]
},
{
'name': '测试','child': [{'name': '回兴'},{'name': '南平'},{'name': '工商学院'}]
}
]
},
{'name' : '北京', 'child': [
{
'name': '北京','child': [{'name': '朝阳'},{'name': '石景山'},{'name': '西单'}]
},
{
'name': '中央电视台','child': [{'name': '天安门'},{'name': '毛主席'},{'name': '小凳子'}]
}
]
}
]
var provinceObj = document.getElementById("province");
var cityObj = document.getElementById("city");
var areaObj = document.getElementById("area");
function init(province, city, area){
var provinceStr = '', cityStr = '', areaStr = '';
arr.map((item, index) => {
if(province == index) {
provinceStr += `<option value="${index}" selected>${item.name}</option>`;
} else {
provinceStr += `<option value="${index}">${item.name}</option>`;
}
if(index == province) {
//遍历城市,每次遍历前,清空城市数组
cityStr = '';
console.log(item.child)
item.child.map((value,key) => {
if( key == city) {
cityStr += `<option value="${key}" selected>${value.name}</option>`;
} else {
cityStr += `<option value="${key}">${value.name}</option>`;
}
if(key == city) {
areaStr = '';
value.child.map((v, k) => {
if(k == area) {
areaStr += `<option value="${k}" selected>${v.name}</option>`;
} else {
areaStr += `<option value="${k}">${v.name}</option>`;
}
})
}
})
}
})
provinceObj.innerHTML = provinceStr;
cityObj.innerHTML = cityStr;
areaObj.innerHTML = areaStr;
}
init(0,1,1);
function changeProvince() {
var pIndex = provinceObj.selectedIndex;
init(pIndex,0,0);
}
function changeCity() {
console.log('__________')
var pIndex = provinceObj.selectedIndex;
var cIndex = cityObj.selectedIndex;
console.log(pIndex,cIndex)
init(pIndex,cIndex,0);
}
</script>
</body>
</html>