jQuery二级联动

时间:2023-01-15 15:29:45
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>二级联动</title>
<script src="js/jquery-1.7.1.js"></script>
<style> </style>
<script type="text/javascript"> $(function(){
var provinces = ['北京', '上海', '浙江'];
var provinceCityMap = {
'北京': ['东城','西城','崇文','宣武','朝阳'],
'上海': ['黄浦','卢湾','徐汇','长宁','静安'],
'浙江': ['杭州','嘉兴','宁波','温州','湖州']
};
var $province = $('#province');
for(var i = 0; i < provinces.length; i++){
$('<option>' + provinces[i] + '</option>')
.appendTo($province)
.val(provinces[i]);
}
$province.on('change', function() {
//当前选中的省的值
var citySelected = $province.find('option:selected').val();
//console.log(citySelected);
changeCitys(citySelected);
});
function changeCitys(province) {
$('.city').empty();
var citys = provinceCityMap[province];
for(var i = 0;i < citys.length;i++){
$('<option>' + citys[i] + '</option>')
.appendTo('.city')
.val(citys[i]);
}
}
changeCitys($province.find('option:selected').val());
$('.show').on('click', function() {
console.log($province.find('option:selected').val());
}); });
</script> </head>
<body> <select id="province"></select> <select class="city"></select> <button class="show">显示</button>
</body>
</html>