全国城市数据.rar 这个js是通过json格式填写的!
- var cityData3 = [{
- value: '110000',
- text: '北京市',
- children: [{
- value: "110101",
- text: "北京市",
- children: [{
- value: "110101",
- text: "东城区"
- }, {
- value: "110102",
- text: "西城区"
- }, {
- .......
html和js的代码如下:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>城市选择</title>
- <meta name="renderer" content="webkit">
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
- <script src="js/jquery-1.8.3.min.js"></script>
- <script src="js/city.data-3.js"></script>
- </head>
- <style type="text/css">
- #city { display: none; }
- #area { display: none; }
- select { float: left; margin-right:10px; }
- </style>
- <body>
- <select name="province" id="province">
- <option value="">---请选择---</option>
- </select>
- <select name="city" id="city">
- <option value="">---请选择---</option>
- </select>
- <select name="area" id="area">
- <option value="">---请选择---</option>
- </select>
- <script>
- $(function(){
- $.each(cityData3, function(index, p){
- //console.log(cityData3[index].text);
- str = "<option value='"+ cityData3[index].value +"'>"+ cityData3[index].text+ "</option>";
- $("#province").append(str);
- });
- $("#province").change(function(){
- var province = $(this).val();
- $("#city").html("").css("display","block");
- var index = $(this).get(0).selectedIndex - 1;
- if(index == -1){
- $("#city").html("<option value=''>---请选择---</option>");
- $("#area").html("<option value=''>---请选择---</option>");
- }else{
- $.each(cityData3[index].children, function(k ,p){
- str = "<option value='"+ p.value +"'>"+ p.text+ "</option>";
- $("#city").append(str);
- })
- }
- //自动弹出三级的第一个内容
- if(cityData3[index]["children"][0]["children"]){
- $("#area").html("").css("display","block");
- $.each(cityData3[index]["children"][0]["children"], function(k ,p){
- str = "<option value='"+ p.value +"'>"+ p.text+ "</option>";
- $("#area").append(str);
- })
- }
- });
- //console.log(cityData3[0]["children"][0]["children"][0]);
- $("#city").change(function(){
- var city = $(this).val();
- $("#area").html("").css("display","block");
- var index = $("#province").get(0).selectedIndex - 1;
- var index2 = $(this).get(0).selectedIndex;
- if(index2 == -1){
- $("#area").html("<option value=''>---请选择---</option>");
- }else{
- $.each(cityData3[index]["children"][index2]["children"], function(k ,p){
- str = "<option value='"+ p.value +"'>"+ p.text+ "</option>";
- $("#area").append(str);
- })
- }
- });
- });
- </script>
- </body>
- </html>
效果:
文章点评