js省市二级联动

时间:2023-03-08 22:03:14

html:

<script src="js/city.js"></script>
......
<body>
<div class="padding border-bottom">
<ul class="search">
<li>
<select style="height:31px;border-radius: 3px;border: solid 1px #ddd;" id="province">
</select>
</li>
<li id="city">
</li>
<li> <a class="button border-main icon-plus-square-o" href="javascript:void(0)" onclick="goaddcity()"> 添加</a> </li>
</ul>
</div>
</body>

city.js:

$(function(){
//加载所有省市
$("#province").html("");
$("#city").html("");
$.ajax({
url: "js/city.json",
type: "get",
dataType: 'json',
contentType: "application/json;charset=utf-8",
success:function(data){
if (data.success == true) {
//i表示在data中的索引位置,n表示包含的信息的对象
//省
var province0 = '<option>----请选择省份----</option> ';
$('#province').append(province0);
//市
var city0 =
'<select style="height:31px;border-radius: 3px;border: solid 1px #ddd;" class="city">'+
' <option>----请选择城市----</option> '+
'</select> '
;
$("#city").append(city0);
$.each(data.data,function(i,n){
var name = n.name;
var province = '<option>'+name+'</option>';
$('#province').append(province);
if (n.regionCityList != null) {
var str = '<select style="height:31px;border-radius: 3px;border: solid 1px #ddd;" class="city">';
var cityarr = n.regionCityList;
for (var i=0;i<cityarr.length;i++){
str += '<option value="'+cityarr[i].code+'">'+cityarr[i].name+'</option>';
}
str += '</select>';
$('#city').append(str);
} }); $(document).ready(function(){
$("#province").change(function(){
$("#province option").each(function(i,o){
if($(this).attr("selected")){
$(".city").hide();
$(".city").eq(i).show();
currentShowCity=i;
}
});
});
$("#province").change();
}); } },
error:function() {
alert("error");
}
}); });
city.json(注意:city.json和city.js要在同一目录下,并且目录文件夹是js)
city.json下载地址: http://files.cnblogs.com/files/007sx/city.zip