jquery之动态级联下拉列表

本文介绍了一种使用jQuery实现省-市级联下拉列表的方法。通过预定义的数据结构和事件监听,当选择省份时,相应的城市选项会动态更新。此方法适用于网页表单中需要地区级联选择的场景。

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

转自:http://yunjianfei.iteye.com/blog/
在制作HTML页面的时候,难免会遇到级联下拉列表的显示。比如最常见的 “省—市” 级联下拉列表。

下面贴出来我的实现方式,供大家参考一下(用的是jquery)。

首先是运行结果:

下面是代码,可以详细看看。

<!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 src="./jquery-2.1.0.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、付费专栏及课程。

余额充值