jquery实现二级联动

时间:2024-01-11 13:01:14

闲来没事,写点jquery练练手。

<!--json代码部分 新建文件liandong.json-->

var pron_city = {
'省':['all'],
'北京':[
{'市':[]},
{'海淀区':[]},
{'东城区':[]},
{'西城区':[]},
{'昌平区':[]},
{'怀柔区':[]},
{'朝阳区':[]}
],
'山东':[
{'市':[]},
{'济南':['区','历城区','历下区','槐荫区','市中区']},
{'青岛':['区','一区','二区']}
],
'河北':[
{'市':[]},
{'石家庄':['区','三区','四区']},
{'唐山':['区','五区','六区']},
{'保定':['区','七区','八区']}
]
}

<!--html代码部分-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style> </style>
</head>
<script src="../js/jquery.js"></script>
<style>
body{background-color:#435a9d;}
ul,li{margin:0;padding:0;}
.abc{
width:420px;
height:480px;
margin:100px;
}
select{
width:110px;
margin-left:10px;
}
</style>
<script src="liandong.json"></script>
<script>
$(document).ready(function(){
for(var i in pron_city){
var html_pn = "<option>"+i+"</option>";
$('.province').append(html_pn);
}
var province , city , index;
$('.province').change(function(){
$('.city,.block').empty();
province = $(this).val();
for(var j in pron_city[province]){
for(var m in pron_city[province][j])
{
var html_cy = "<option>"+m+"</option>";
$('.city').append(html_cy);
}
}
})
$('.city').change(function(){
$('.block').empty();
city = $(this).val();
index = $(this)[0].selectedIndex;
for(var k in pron_city[province][index][city]){
html_bk = "<option>"+pron_city[province][index][city][k]+"</option>";
$('.block').append(html_bk);
}
}) })
</script>
<body>
<div class="abc">
<select class="province">
</select>
<select class="city">
<option selected>市</option>
</select>
<select class="block">
<option selected>区</option>
</select>
</div>
</body>
</html>