首先先把城市信息封装在数组中,需要三维数组存放省、市、区的城市信息。代码如下:
var provinces =['山西','山东','河南','河北'];
var cities = [
['太原','晋中','大同','阳泉'],
['济南','青岛','威海'],
['郑州','洛阳'],
['石家庄','保定']
];
var areas = [
[
['小店','迎泽','杏花岭','尖草坪'],
['榆次','左权','寿阳'],
['左云'],
['平定','盂县']
],
[
['章丘','天桥'],
['黄岛','城阳'],
['环翠区','文登区'],
],
[
['中原','上街'],
['洛龙','吉利'],
],
[
['新华','桥西'],
['清苑','徐水'],
],
]
具体实现
<script>
//html元素全部加载完毕执行
/*$(document).ready(function () {
})*/
$(function () {
//遍历有哪些省
$(provinces).each(function(i,o){ //i获得省的下标,o对应的值
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#province').append(str);
});
$('#province').on('change',function () { //选中省之后,添加事件
pIndex = $('#province').find(':selected').attr('value'); //获得选中省的下标
$('#city').empty().append("<option value=\"\">请选择</option>");
$('#area').empty().append("<option value=\"\">请选择</option>");
$(cities[pIndex]).each(function (i,o) {
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#city').append(str);
});
});
$('#city').on('change',function(){
cIndex = $('#city').find(':selected').attr('value');
$('#area').empty().append("<option value=\"\">请选择</option>");
$(areas[pIndex][cIndex]).each(function(i,o){
var str = "<option value=\""+i+"\">"+o+"</option>";
$('#area').append(str);
})
});
});
</script>
</head>
<body>
<select name="" id="province">
<option value="">请选择</option>
</select>省
<select name="" id="city">
<option value="">请选择</option>
</select>市
<select name="" id="area">
<option value="">请选择</option>
</select>县
</body>
转载:https://blog.csdn.net/zycn0483/article/details/101384349
查看评论