<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div align="center">
省:
<select id="province" onchange="findcity()">
<option>-------请选择省份-------</option>
</select>
市:
<select id="city" onchange="findqu()">
<option>-------请选择城市-------</option>
</select>
区:
<select id="qu">
<option>-------请选择所在区-------</option>
</select>
</div>
</body>
<script>
//json数据省、市、区
data1 = [{
title: '江西',
id: 1,
children: [{
title: '南昌',
id: 1000,
children: [{
title: '青山湖区',
id: 10001
}, {
title: '高新区',
id: 10002
}]
}, {
title: '九江',
id: 1001
}, {
title: '赣州',
id: 1002
}]
}, {
title: '广西',
id: 2,
children: [{
title: '南宁',
id: 2000
}, {
title: '桂林',
id: 2001
}]
}, {
title: '陕西',
id: 3,
children: [{
title: '西安',
id: 3000
}, {
title: '延安',
id: 3001
}]
}]
// console.log(data1);
//获取省份
var province = document.getElementById("province");
for (var i = 0; i < data1.length; i++) {
//给身份的option赋初值
var option = province.appendChild(document.createElement("option"));
option.innerText = data1[i].title;
option.value = data1[i].id;
}
var city = document.getElementById("city");
// 根据省份去找城市
function findcity() {
//清空之前的html防止改变省份之后重复添加
removechild(city, "城市");
//根据省份value值查询data1中id为value的数据
var id = parseInt(index(province.value));
var children = data1[id].children;
//防止不存在children
if (children == undefined) {
return;
}
//给城市赋值
for (var i = 0; i < children.length; i++) {
var option = city.appendChild(document.createElement("option"));
option.innerText = children[i].title;
option.value = children[i].id;
}
}
//根据i该条数据在data1中的位置
function index(a) {
for (var i = 0; i < data1.length; i++) {
if (data1[i].id == a) {
return i;
}
}
}
//清空之前的html
function removechild(element, str) {
var citychildren = element.children;
for (var i = 0; i < citychildren.length; i++) {
citychildren[i].remove();
}
element.innerHTML = "<option>-------请选择" + str + "-------</option>";
}
var qu = document.getElementById("qu");
function findqu() {
removechild(qu, "区");
//根据省份id,城市id确定该条数据的位置
var id1 = parseInt(index(province.value));
var id2 = parseInt(city.value);
var children = data1[id1].children;
//防止不存在children
if (children == undefined) {
return;
}
for (var i = 0; i < children.length; i++) {
//防止不存在children
if (children[i].id == id2) {
var children2 = children[i].children;
//防止不存在children
if (children2 == undefined) {
return;
}
//给区赋值
for (var i = 0; i < children2.length; i++) {
var option = qu.appendChild(document.createElement("option"));
option.innerText = children2[i].title;
option.value = children2[i].id;
}
}
}
}
</script>
</html>
效果图