html部分
<!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>
<select name="省" id="sheng" onchange="shii(this)">
<option>省份</option>
</select>
<select name="市" id="shi" onchange="quu(this)">
<option>市</option>
</select>
<select name="区" id="qu"onchange="quu(this)">
<option> 区</option>
</select>
<script src="./2省市区三级联动.js"></script>
</body>
</html>
js部分
var sheng = document.querySelector('#sheng')
var shi = document.querySelector("#shi")
var qu = document.querySelector("#qu")
function shengg() {
var pl = province.length;
for (var i = 0; i < pl; i++) {
var so = document.createElement("option")
so.innerText = province[i]['pn']
so.value = i
sheng.appendChild(so)
}
}
function shii(xc) {
var s = xc.options[xc.selectedIndex].value
if (s >= 0) {
shi.style.display = "inline-block"
qu.style.display = "none"
} else {
shi.style.display = "none"
qu.style.display = "none"
}
if (s != null) {
shi.length = 1;
var cl = province[s]['cn'].length;
for (var j = 0; j < cl; j++) {
var shio = document.createElement("option")
shio.innerText = province[s]["cn"][j].cityn
shio.value = j
shi.appendChild(shio)
}
}
}
function quu(sc) {
var q = sc.options[sc.selectedIndex].value
if (q >= 0) {
qu.style.display = "inline-block"
} else {
qu.style.display = "none"
}
var qq=q
if (q != null) {
qu.length = 1;
var ql = province[qq]['cn'][q].countyn.length;
for (var z = 0; z < ql; z++) {
var quo = document.createElement("option")
quo.innerText = province[qq]["cn"][q].countyn
quo.value = z
qu.appendChild(quo)
}
}
}
var province = [
{
pn: "北京",
cn: [
{
cityn: "北京",
countyn: ["东城区", "西城区", "崇文区"]
}
]
},
{
pn: "江苏",
cn: [
{
cityn: "苏州",
countyn: ["姑苏区", "吴中区", "虎丘区"]
},
{
cityn: "南京",
countyn: ["玄武区", "秦淮区", "鼓楼区"]
},
{
cityn: "扬州",
countyn: ["邗江区", "广陵区", "江都区"]
}
]
},
{
pn: "重庆",
cn: [
{
cityn: "重庆",
countyn: ["姑苏区", "吴中区", "虎丘区"]
}
]
}
]
shengg()