准备
下载jquery
json数据:https://download.youkuaiyun.com/download/qq_47699076/13739982
简介
使用jquery操控dom对象,触发js事件来完成地址二级联动
源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>地址二级联动</title>
<script src="../jquery/jquery-3.2.1.js"></script>
<!-- <link rel="stylesheet" href="../bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">
<script src="../bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> -->
<script src="../data/city_code.js"></script>
<script>
$(document).ready(function () {
var shi_qu = []
for (let i = 0; i < datas.length; i++) {
var op = $("<option></option>");
op.append(datas[i].name);
op.attr("value", datas[i].code);
$("#sheng").append(op);
}
if ($(":selected").html() == "北京市") {
create_for();
}
$("#sheng").change(function () {
create_for();
});
$("#shi").change(function () {
console.log($("#shi").find("option:selected").text());
create_qu_for()
});
function create_shi(name, code) {
var op = $("<option></option>");
op.append(name);
op.attr("value", code);
$("#shi").append(op);
}
function create_qu(name, code) {
var op = $("<option></option>");
op.append(name);
op.attr("value", code);
$("#qu").append(op);
}
function create_for() {
for (let i = 0; i < datas.length; i++) {
if ($(":selected").html() == datas[i].name) {
console.log(datas[i].city);
let city_s = datas[i].city;
shi_qu = []
shi_qu = city_s
$("#shi").empty()
$("#qu").empty()
for (let j = 0; j < city_s.length; j++) {
create_shi(city_s[j].name, city_s[j].code);
}
break;
}
}
}
function create_qu_for(){
for (let i = 0; i < shi_qu.length; i++) {
if ($("#shi").find("option:selected").text() == shi_qu[i].name) {
console.log(shi_qu[i].area);
let qu_txt = shi_qu[i].area;
$("#qu").empty();
for (let j = 1; j < qu_txt.length; j++) {
console.log(qu_txt[j].name);
create_qu(qu_txt[j].name, qu_txt[j].code);
}
}
}
}
});
</script>
</head>
<body>
<div style="position: relative;font-size: 18px;">
<div style="float: left;margin: 50px;">
<span>省份: </span>
<select name="" id="sheng" style="width: 200px;height: 31px;"></select>
</div>
<div style="float: left;margin: 50px;">
<span>城市: </span>
<select name="" id="shi" style="width: 200px;height: 31px;"></select>
</div>
<div style="float: left;margin: 50px;">
<span>区(县): </span>
<select name="" id="qu" style="width: 200px;height: 31px;"></select>
</div>
</div>
</body>
</html>
效果展示