jQuery实现省级三联动【使用art-template 模板】

直接上代码:

<!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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值