二级联动代码

本文介绍了一种基于jQuery的多级联动选择器实现方法,主要用于用户填写地址时的省份和城市选择。通过自定义jQuery插件实现了当省份发生变化时,对应的城市列表随之更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

经常会用的多级联动的需求,今天总结一下,大多数是用在填写用户地址的时候,

具体代码如下:引入jQuery文件,直接拷到html文件中就可以运行了;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

  <title>二级级联</title> 

  <script type="text/javascript" src="js/jquery.min.js"></script>

 

<script> 

$.fn.extend({ 

  parent_select_change: function(province) { 

    $("#child_select").empty(); 

 

    var parent = $("#parent_select").val(); 

 

    if (parent == ''){ 

      return false

    } 

    var cities = null

    for(var i=0; i < province.length; i++) { 

      var p = province[i]; 

      if(p.id == parent){ 

        cities = p.city

        break

      } 

    } 

 

    for(var i=0; i < cities.length; i++) { 

      city = cities[i]; 

      var o = new Option(city.name,city.cid); 

      $("#child_select").append(o); 

    } 

  }, 

 

  show_province_items: function() { 

    var resp = [ 

      { 

        "id" : 1

        "name" : "山西"

        "city" : [{ 

          "cid" : 1

          "name" : "太原"

        }, { 

          "cid" : 2

          "name" : "临汾"

        } 

        ], 

      }, 

      { 

        "id" : 2

        "name" : "陕西"

        "city" : [{ 

          "cid" : 3

          "name" : "榆林"

        }, { 

          "cid" : 4

          "name" : "西安"

        } 

        ], 

      }, 

    ]; 

 

    //以上为模拟数据,可以用getJSON的方式,从服务器端取回来数据 

    //$.getJSON("/province", function(resp){ 

        var html = "" 

        var pro = resp 

        html += "<option value=''> --请选择-- </option>" 

        if(pro){ 

          for(var i=0; i < pro.length; i++) { 

            var p = pro[i]; 

            html += "<option value='" + p.id + "'>" + p.name + "</option>" 

          } 

        } 

 

        $("#parent_select").empty(); 

        $("#parent_select").html(function(i,origText){ 

          return html

        }); 

 

        $("#parent_select").change(function(){ 

          $(this).parent_select_change(pro); 

        }); 

    //}); 

  } 

}); 

 

$(document).ready(function(){ 

   $(this).show_province_items();  

}); 

</script> 

 

</head> 

 

<body> 

  <center>  

 <h1>级联列表</h1> 

  省:<select id='parent_select' name='province'></select>  市:<select id='child_select' name='city'></select> 

 

  <br> 

  </center> 

</body> 

</html> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值