效果图
html+css
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>珠峰培训-省市县级联菜单</title>
<link rel="stylesheet" href="css/reset.min.css">
<style>
.menu {
margin: 20px auto;
padding: 20px;
width: 360px;
border: 1px solid lightblue;
}
.menu select {
display: inline-block;
margin-right: 10px;
padding: 0 5px;
width: 100px;
height: 30px;
line-height: 30px;
border: 1px solid #DDD;
}
</style>
</head>
<body>
<div class="menu">
<select name="region" id="province">
<option value="">请选择</option>
</select>
<select name="region" id="city">
<option value="">请选择</option>
</select>
<select name="region" id="county">
<option value="">请选择</option>
</select>
</div>
<script src="./js/jquery-1.11.3.min.js"></script>
<script src="./js/index2.js"></script>
</body>
</html>
js
let val;
$.ajax({
url: "./json/regionData.json",
type: "get",
async: false,
success: function (data) {
let arr = formData(0, data);
$("#province").html(bindHtml(arr));
$("#province").change(function () {
val = $(this).val();
let arr = formData(1, data);
$("#city").html(bindHtml(arr));
county.length = 1;
})
$("#city").change(function () {
val = $(this).val();
let arr = formData(2, data);
$("#county").html(bindHtml(arr));
})
}
})
function formData(level, data) {
let result = [];
let ary = null;
if (level === 0) {
$.each(data, function (index, item) {
result.push(item.name);
})
}
if (level === 1) {
$.each(data, function (index, item) {
if (val === item.name) {
ary = item.city;
}
})
$.each(ary, function (index, item) {
result.push(item.name)
})
}
if (level === 2) {
$.each(data, function (index, item) {
$.each(item.city, function (index, item) {
if (val === item.name) {
result = item.area;
}
})
})
}
return result;
}
function bindHtml(arr) {
let str = `<option value="">请选择</option>`;
$.each(arr, function (index, item) {
str += `<option value="${item}">${item}</option>`
})
return str;
}