直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>省级三联动</title>
<style>
.form-group{
float: left;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="form-group">
<select name="" id="provice">
<option value="">请选择省份</option>
</select>
</div>
<div class="form-group">
<select name="" id="city">
<option value="">请选择城市</option>
</select>
</div>
<div class="form-group">
<select name="" id="area">
<option value="">请选择县城</option>
</select>
</div>
</div>
</body>
<script src="jquery-1.11.1.min.js"></script>
<script src="template-web.js"></script>
<script type="text/html" id="tpl01">
<option value="">请选择省份</option>
{{each provice}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script type="text/html" id="tpl02">
<option value="">请选择城市</option>
{{each citys}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script type="text/html" id="tpl03">
<option value="">请选择县城</option>
{{each areas}}
<option value="{{$value.id}}">{{$value.name}}</option>
{{/each}}
</script>
<script>
// 获取省份的数据
$.ajax({
type: 'get',
url: 'http://localhost:3000/province',
success: function(res){
console.log(res)
var html = template('tpl01', {'provice': res})
$('#provice').html(html)
}
})
// 为省份添加点击事件
$('#provice').change(function(){
// 获取省份的 id
let pid = this.value
$.ajax({
type: 'get',
url: 'http://localhost:3000/cities',
data: {
id: pid
},
success: function(res){
console.log(res)
let html = template('tpl02', {'citys': res})
// 当选择省份的时候,应该将现成的内容清除 ,变成请选择县城
let htmlarea =template('tpl03', {'areas': []})
$('#area').html(htmlarea)
$('#city').html(html)
}
})
})
// 为城市添加事件
$('#city').change(function(){
var cid = this.value
$.ajax({
type: 'get',
url: 'http://localhost:3000/areas',
data: {
id: cid
},
success: function(res){
console.log(res)
let html =template('tpl03', {'areas': res})
$('#area').html(html)
}
})
})
</script>
</html>