首先是我们的json数据,这里只粘几个省份的信息就好了,主要是展示结构,方便下面的理解
首先引用jQuery,然后在body体内给出两个select选择框,加上id选择器
下面就是完整的代码了:
<body>
<select name="province" id="province"></select>
<select name="city" id="city"></select>
<script>
$.ajax({
url: "allArea.json",
type: "get",
dataType: "json",
success: function (retJson) {
renderList(retJson)
}
})
function renderList(jsonObj) {
var allProvinces = jsonObj.provinces
// 得到所有省份的数据
$("#province").empty()
// 这里利用forEach循环添加省份的数据
allProvinces.forEach(function(element) {
var option = $(`<option value="${element.name}">${element.name}</option>`)
// option.appendTo("#province")
$("#province").append(option)
});
// 给省份的选择框添加change事件
$("#province").change(function () {
var curProvince = $("#province>option:selected").val();
// 得到当前选中的省份的val值
var selectedProvince = allProvinces.find(function (curElement, index) {
// find() 方法获得当前元素集合中每个元素的后代,通过选择器、jQuery 对象或元素来筛选。
return curElement.name == curProvince;
// 将当前选中省份的名字返回给 selectedProvince
})
var allCities = selectedProvince.cities;
// allCities指当前被选中省份下的所有城市
$("#city").empty()
// select之前选中显示的文本还残留在select框里,为了去掉残留的文本,需要清空城市选择框的内容
// 这里利用forEach循环添加城市的数据
allCities.forEach(function (element) {
var option = $(`<option value="${element.name}">${element.name}</option>`)
option.appendTo("#city");
});
})
$("#province").triggerHandler("change");
// 这个方法将会触发指定的事件类型上所有绑定的处理函数。但不会执行浏览器默认动作,也不会产生事件冒泡。
}
</script>
</body>
省份的选择:
城市的选择: