使用基于前端技术技术的jquery实现省市区三级联动
2. 定义三个select标签,引入js文件
<head>
<meta charset="utf-8">
<title>中国三级联动</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="area_chs.js"></script>
</head>
<body>
<select id="province"></select>
<select id="city"></select>
<select id="area"></select>
<button id="btn" onclick='f()'>提交</button>
</body>
3.初始化,使用let定义几个变量
let province = '';
let provinceIndex = 0;
let city = '';
let cityIndex = 0;
let area = ''
4.select初始化,使用map方法
_areaList.map((item, index) => {
$("#province").append(`<option value=${item.name} index=${index}>${item.name}</option>`);
})
_areaList[provinceIndex].city.map((item, index) => {
$("#city").append(`<option value=${item.name} index=${index}>${item.name}</option>`);
})
city = $('#city').val();
$("#area").empty()
_areaList[provinceIndex].city[cityIndex].area.map((item, index) => {
$("#area").append(`<option value=${item}>${item}</option>`);
})
area = $('#area').val();
5.当下拉发生改变时,对应的变量值也发送改变
$('#province').change(function () {
province = $('#province').val();
provinceIndex = $('#province')[0].selectedIndex;
init()
})
$('#city').change(function () {
city = $('#city').val();
cityIndex = $('#city')[0].selectedIndex;
setArea(provinceIndex, cityIndex);
})
$('#area').change(function () {
area = $('#area').val()
})
6.最后使用形式如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>中国三级联动</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="area_chs.js"></script>
</head>
<body>
<select id="province"></select>
<select id="city"></select>
<select id="area"></select>
<button id="btn" onclick='f()'>提交</button>
</body>
<script type="text/javascript">
let province = '';
let provinceIndex = 0;
let city = '';
let cityIndex = 0;
let area = ''
_areaList.map((item, index) => {
$("#province").append(`<option value=${item.name} index=${index}>${item.name}</option>`);
})
// 当选择发生改变时记录值
$('#province').change(function () {
province = $('#province').val();
provinceIndex = $('#province')[0].selectedIndex;
init()
})
$('#city').change(function () {
city = $('#city').val();
cityIndex = $('#city')[0].selectedIndex;
setArea(provinceIndex, cityIndex);
})
$('#area').change(function () {
area = $('#area').val()
})
// 根据省份设置市区的下拉
function setCity(provinceIndex) {
$("#city").empty()
_areaList[provinceIndex].city.map((item, index) => {
$("#city").append(`<option value=${item.name} index=${index}>${item.name}</option>`);
})
city = $('#city').val();
}
// 根据市区设置区的下拉
function setArea(provinceIndex, cityIndex) {
$("#area").empty()
_areaList[provinceIndex].city[cityIndex].area.map((item, index) => {
$("#area").append(`<option value=${item}>${item}</option>`);
})
area = $('#area').val();
}
// 根据省份初始化
function init() {
cityIndex = 0;
setCity(provinceIndex);
setArea(provinceIndex, cityIndex);
province = $('#province').val();
}
init()
function f() {
console.log(province + city + area);
}
</script>
</html>