省市区三级联动

image-20240219141517982

  • 创建3个select,每次给对应的select里new对应的option
  • 需要注意的是,每次select变化的时候,需要清空之前的状态,否者会有bug
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
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<p align="center">
省:<select name="" id="sel1">
<option value="">请选择</option>
</select>
市:<select id="sel2"></select>
区:<select id="sel3"></select>
</p>
你选择的地址是:<h1 id="address"></h1>
</body>
<script src="city.js" type="text/javascript" charset="utf-8"></script>
<script>
var sel1 = document.getElementById("sel1")
var sel2 = document.getElementById("sel2")
var sel3 = document.getElementById("sel3")
var h1 = document.getElementById('address')

var cityArr = []
var areaArr = []

provice.forEach(v => {
var option = new Option(v.name);
sel1.options.add(option);
})

sel1.onchange = function () {
console.log(this.selectedIndex);
sel1Index = this.selectedIndex - 1;
sel2.options.length = 0;
sel3.options.length = 0;

if (sel1Index !== -1) {

cityArr = provice[sel1Index].city;
cityArr.forEach(v => {
var option = new Option(v.name);
sel2.options.add(option);
})

areaArr = cityArr[0].districtAndCounty

// console.log(areaArr);


areaArr.forEach(v => {
var option = new Option(v);
sel3.options.add(option);
})
h1.innerText = `${provice[sel1Index].name}${cityArr[0].name}${areaArr[0]}`

} else {
h1.innerText = "";
}

}

var sel2Index = 0;

sel2.onchange = function () {
sel2Index = this.selectedIndex;
areaArr = cityArr[sel2Index].districtAndCounty;
// console.log(areaArr);
sel3.options.length = 0;

areaArr.forEach(v => {
var option = new Option(v);
sel3.options.add(option);
})
h1.innerText =
`${provice[sel1Index].name}${cityArr[sel2Index].name}${areaArr[0]}`

}

var sel3Index = 0;
sel3.onchange = function () {
sel3Index = this.selectedIndex;
// console.log(sel3Index);
h1.innerText = `${provice[sel1Index].name}${cityArr[sel2Index].name}${areaArr[sel3Index]}`

}


</script>

</html>