基于Jquery的级联选择器
时间: 2024-05-03 22:17:43 浏览: 19
以下是一个基于jQuery的级联选择器示例代码:
HTML部分:
```html
<select id="province">
<option value="-1">请选择省份</option>
<option value="1">北京市</option>
<option value="2">上海市</option>
<option value="3">天津市</option>
<option value="4">重庆市</option>
</select>
<select id="city">
<option value="-1">请选择城市</option>
</select>
<select id="district">
<option value="-1">请选择区县</option>
</select>
```
jQuery部分:
```javascript
$(function() {
// 省份改变时更新城市列表
$('#province').on('change', function() {
var provinceId = $(this).val();
if (provinceId === '-1') {
$('#city').html('<option value="-1">请选择城市</option>');
$('#district').html('<option value="-1">请选择区县</option>');
return;
}
$.ajax({
url: 'getCityList.php',
type: 'GET',
data: {
provinceId: provinceId
},
dataType: 'json',
success: function(response) {
var cityHtml = '<option value="-1">请选择城市</option>';
for (var i = 0; i < response.length; i++) {
cityHtml += '<option value="' + response[i].id + '">' + response[i].name + '</option>';
}
$('#city').html(cityHtml);
$('#district').html('<option value="-1">请选择区县</option>');
},
error: function() {
alert('获取城市列表失败');
}
});
});
// 城市改变时更新区县列表
$('#city').on('change', function() {
var cityId = $(this).val();
if (cityId === '-1') {
$('#district').html('<option value="-1">请选择区县</option>');
return;
}
$.ajax({
url: 'getDistrictList.php',
type: 'GET',
data: {
cityId: cityId
},
dataType: 'json',
success: function(response) {
var districtHtml = '<option value="-1">请选择区县</option>';
for (var i = 0; i < response.length; i++) {
districtHtml += '<option value="' + response[i].id + '">' + response[i].name + '</option>';
}
$('#district').html(districtHtml);
},
error: function() {
alert('获取区县列表失败');
}
});
});
});
```
以上代码实现了一个简单的级联选择器,当省份发生改变时,会向服务器请求对应的城市列表,并更新城市下拉框;当城市发生改变时,会向服务器请求对应的区县列表,并更新区县下拉框。服务器端需要实现相应的接口,返回对应的城市和区县数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)