code
- 使用jQuery造个三级联动的轮子。
- 其中所引入的city.js是一个省市县的JSON数据provice,若有需要,可以前往下载:传送门
- 代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>三级联动</title>
<style>
*,
*::before,
*::after{
margin: 0;
padding: 0;
}
form{
text-align: center;
margin-top: 50px;
}
</style>
<script src="js/jQ3_3_1.js"></script>
<script src="js/city.js"></script>
</head>
<body>
<form action="#">
<label>您选择的是:<input id="result" type="text" value="" ></label>
<br/><br/>
<select id="provice" onchange="showProvice(this)">
<option>---请选所在省份---</option>
</select>
<select id="city" oninput="showCity(this)">
<option>---请选所在城市---</option>
</select>
<select id="county" onchange="showCounty(this)">
<option>---请选所在县区---</option>
</select>
<button type="button" onclick="showAddress()">确定</button>
</form>
<script>
function myRender($dom,data){
data.forEach(v=>{
$dom.append(` <option>${v.name}</option>`)
})
}
$(function () {
myRender($("#provice"),provice)
})
function showProvice(ele) {
$("#city").find("option:gt(0)").remove()
$("#county").find("option:gt(0)").remove()
$("#result").val("")
let index = $(ele).find("option:selected").index();
$(ele).attr("data-index",index)
myRender($("#city"),provice[index-1].city)
$(ele).find("option:first").attr("disabled",true)
}
function showCity(ele) {
$("#county").find("option:gt(0)").remove()
$("#result").val("")
let preIndex = $("#provice").attr("data-index");
let nextIndex = $(ele).find("option:selected").index();
$(ele).attr("data-index",nextIndex)
if (!provice[preIndex-1].city[nextIndex-1]){
return;
}
let county = provice[preIndex-1].city[nextIndex-1].districtAndCounty;
county.forEach(v=>{
$("#county").append(` <option>${v}</option>`)
})
}
function showCounty(ele) {
let nextIndex = $(ele).find("option:selected").index();
$(ele).attr("data-index",nextIndex)
$("#result").val("")
}
function showAddress() {
if ( !$("#provice").val().indexOf("---")|| !$("#city").val().indexOf("---")|| !$("#county").val().indexOf("---")){
alert("请选择正确的地址再提交!!")
return;
}
let addressInfo = `${$("#provice").val()}-${$("#city").val()}-${$("#county").val()}`;
$("#result").val(addressInfo)
}
</script>
</body>
</html>