<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>城市二级联动</title>
<style>
#provice, #city {
width: 100px;
height: 30px;
}
select {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="provice">
<select name="" id="provice_select" onchange="selectProvice()">
</select>
</div>
<br>
<div id="city">
<select name="" id="city_select" onchange="selectCity()">
</select>
</div>
<br>
<button id="btn" onclick="submit()">提 交</button>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
// 初始化获取数据
var ajaxData = [
{
'provice': '北京市',
'city': ['北京市']
},
{
'provice': '上海市',
'city': ['上海市']
},
{
'provice': '江苏省',
'city': ['南京市', '苏州市', '无锡市', '常州市', '南通市', '泰州市', '扬州市', '盐城市', '镇江市', '宿迁市', '淮安市', '徐州市', '连云港市']
},
{
'provice': '浙江省',
'city': ['杭州市', '建德市', '富阳市', '临安市', '宁波市', '余姚市', '慈溪市', '奉化市', '温州市', '瑞安市', '乐清市', '嘉兴市', '海宁市', '平湖市', '桐乡市', '湖州市', '绍兴市', '诸暨市', '上虞市', '嵊州市', '金华市', '兰溪市', '义乌市', '东阳市', '永康市', '衢州市', '*市', '舟山市', '台州市', '温岭市', '临海市', '丽水市', '龙泉市']
}
]
// 提交后返回数据
var backData = {
'provice': '江苏省',
'city': '泰州市'
}
var selectedProvice = '', selectedCity = '', strProvice = '', strCity = '', index = 0
// 初始化
// 初始化省份
function getProvice (selectedData) {
// 清空
strProvice = ''
$('#provice_select').empty()
// 渲染
$.each(ajaxData, function(index, el) {
strProvice += '<option value="' + el.provice + '">' + el.provice + '</option>'
});
$('#provice_select').append(strProvice)
index = $('#provice_select option:selected').index()
// 默认选中
if (selectedData) {
$('#provice_select').find('option[value=' + selectedData.provice + ']').attr('selected', true);
}
index = $('#provice_select option:selected').index()
getCity(index, selectedData.city)
}
// 初始化城市
function getCity (index, selectedData) {
// 清空
strCity = ''
$('#city_select').empty()
// 渲染
$.each(ajaxData[index].city, function(index, el) {
strCity += '<option value="' + el + '">' + el + '</option>'
});
$('#city_select').append(strCity)
// 默认选中
if (selectedData) {
$('#city_select').find('option[value=' + selectedData + ']').attr('selected', true);
}
}
// 选择省份
function selectProvice () {
selectedProvice = $('#provice_select option:selected').val()
index = $('#provice_select option:selected').index()
selectCity()
}
// 选择城市
function selectCity () {
selectedCity = $('#city_select option:selected').val()
getCity(index, selectedCity)
}
// 提交
function submit () {
selectProvice()
backData.provice = selectedProvice
backData.city = selectedCity
console.log(backData)
}
getProvice(backData)
</script>
</body>
</html>