Jquery zTree 插件实现简单的省市下拉

使用到了以下接口和插件

腾讯位置服务:

http://lbs.qq.com/webservice_v1/guide-region.html

Jquery tree 插件

http://www.treejs.cn/v3/main.php#_zTreeInfo

 

效果:

 

代码实现:

 

1. 首先引入脚本(建议自行下载,这里引用的是CDN): 

<link href="https://cdn.bootcss.com/zTree.v3/3.5.33/css/zTreeStyle/zTreeStyle.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/1.4.2/jquery.min.js"></script> <script src="https://cdn.bootcss.com/zTree.v3/3.5.33/js/jquery.ztree.core.min.js"></script> <script src="https://cdn.bootcss.com/zTree.v3/3.5.33/js/jquery.ztree.excheck.min.js"></script>

 

2. html:

<div class="provinces-cities">
    <ul id="treeDemo" class="ztree"></ul>
</div>

 

3. css: 

       .provinces-cities {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            padding: 5px 10px;
            overflow-y: scroll;
            border: 1px solid #e2e2e2;
            border-bottom-left-radius: 5px;
            border-top-left-radius: 5px;
        }

 

4. js (注意ajax 请求的参数key的值为你自己申请的密钥): 

    var zTreeObj;
    // zTree configuration information, refer to API documentation (setting details)
    var setting = {
        check: {
            enable: true,
            chkboxType : { "Y" : "ps", "N" : "ps" }
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    // zTree data attributes, refer to the API documentation (treeNode data details)
    var zNodes = [];
    $(document).ready(function(){
        $.ajax({
            //OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77
            type : 'GET',//请求类型
            url : 'https://apis.map.qq.com/ws/district/v1/list?key=你申请的密钥&output=jsonp&callback=?',//请求地址,这里的key参数需要自行注册获取应用key,注册地址(http://lbs.qq.com/webservice_v1/guide-region.html)
            data : '',//请求数据,String型
            async : true,//是否为异步
            cache : false,//是否缓存
            dataType:'jsonp',//指定jsonp类型
            success : function(data){
                if(!data || data.status != 0) return;
                zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes.concat(nodeWrapper(data.result)));
            }
        });
    });

    function nodeWrapper (rowData) {
        if(!Array.isArray(rowData)) return [];
        var provinces = rowData[0] || [];
        var cities = rowData[1] || [];
        provinces.forEach(function(province) {
            province['open'] = false;
        });

        cities.forEach(function(city) {
            city['pId'] = city.id.substring(0, 2) + '0000';
            city['open'] = false;
            provinces.push(city);
        })
        return provinces;
    }

    function submit() {
        var checkedCities = zTreeObj.getCheckedNodes();
        console.log(checkedCities);
    }

 

posted @ 2018-08-28 20:59  KingCong  阅读(916)  评论(0编辑  收藏  举报