selectCity.js 7.88 KB
/**
 * 选择城市插件
 * 使用:
 * 1. 创建一个DIV做为容器, 然后设置变量
 使用方式一:
 var config = {
 //存放列表的容器
            box: "#cityBox"
            //各个下拉的名字, 可以不指定
            , names: {
                province : "obj.enterprise.province"
                , city: "obj.enterprise.city"
                , county: "obj.enterprise.county"
                , text: "obj.address"
            }
//            省, 市, 区/县的默认值
            ,vals: [
                151, 3001, 1510103
            ]
 //默认的区/县值. 自动查询省市
            ,val: 1510103
        }

 var sCity = $.selectCity(config);

 使用方式二:
 主要区别是将插件绑定在界面元素上. 可以支持一个页面多插件
 var config = {
            //各个下拉的名字, 可以不指定
            names: {
                province : "obj.enterprise.province"
                , city: "obj.enterprise.city"
                , county: "obj.enterprise.county"
                , text: "obj.address"
            }
//            省, 市, 区/县的默认值
            ,vals: [
                151, 3001, 1510103
            ]
 //默认的区/县值. 自动查询省市, val / vals二选一, 默认使用val
            ,val: 1510103
        }

 var sCity = $("#cityBox").selectCity(config);

 */
(function ($) {

    var config = {
        //存放列表的容器
        box: ""
        //根对象
        , root : {}
        //各个下拉的名字
        , names: {
            //省
            province : "province"
            //市
            , city: "city"
            //区
            , county: "county"
            //文本
            , text: ""
        }
        //默认值
        ,vals:[]
        ,val:""
        //请求地址
        , url: "http://192.168.1.208/city/getCityJsonpList.do?parentId="
        , peggingUrl: "http://192.168.1.208/city/getParentCityJsonpList.do?cityId="
    }


    var html = '<select class="citySelect address_province" name="$province" sublevel="address_city" data-hint="省"></select>'
                + '<select class="citySelect address_city" name="$city" sublevel="address_county"  data-hint="市"></select>'
                + '<select class="citySelect address_county" name="$county"  data-hint="区/县"></select>'
                + '<input type="hidden" name="$text" class="citySelect address_text" value=""/>';

    var vp, vcity, vcounty;

    function sCity(config){
        var self = this;
        self.config = config;
        this.insertHtml();
        this.bind();
        if(self.config.val && self.config.val != ""){
            self.fillListForVal(self.config.val);
        } else {
            var dv = self.config.vals;
            self.fillList(self.obj.province, "", dv);
        }
    }

    sCity.prototype.fillListForVal = function(val) {
        var self = this;
        var pegging = self.config.peggingUrl + val;
        $.ajax({
            url: pegging
            , dataType: "jsonp", success: function(data) {
                var vals = new Array();
                for (var i in data){
                    var item = data[i];
                    vals.unshift(item.regionId);
                }

                self.fillList(self.obj.province, "", vals);
            }
        });
    };

    /**
     * 初始化列表
     * 根据父级ID号获取列表
     * 同时根据列表设置默认值
     */
    sCity.prototype.fillList = function (list, id, vals) {
        var self = this;
        var tempUrl = self.config.url;
        if (id) {
            tempUrl += id;
        }
        var def = "";
        if(vals instanceof Array && vals && vals.length > 0){
            def = vals.shift();
        }

        $.ajax({
            url: tempUrl, dataType: "jsonp", success: function (data) {
                self.cleanAddress(list, id);
                for (var i = 0; i < data.length; i++) {
                    var d = data[i];
                    var selected = ""
                    if(def == d.regionId){
                        selected = "selected"
                    }
                    var option = $("<option value='" + d.regionId + "' "+selected+">" + d.regionName + "</option>");
                    list.append(option);
                }

                self.fillNext(list, def, vals, id);
                self.refreshText();
            }, error: function (e) {
            }
        });
    }

    /**
     * 填充下一级
     * @param obj
     * @param id
     * @param def
     */
    sCity.prototype.fillNext = function(obj, id, def, parent){
        var self = this;
        var sub = self.fetchSub(obj);
        if (sub) {
            if (id == null || id == "") {
                self.cleanAddress(sub, parent);
                return;
            }
            self.fillList(sub, id, def);
        }
    }

    /**
     * 清除下拉
     * @param list
     */
    sCity.prototype.cleanAddress = function (list, def) {
        var self = this;
        list.html("");
        var hint = list.data("hint");
        list.append("<option value='"+def+"'>"+hint+"</option>");
        var sub = self.fetchSub(list);
        if (sub) {
            self.cleanAddress(sub, def);
        }
    }

    /**
     * 清除所有
     */
    sCity.prototype.cleanAllAddress = function () {
        var self = this;
        self.fillList(self.obj.province);
    }

    /**
     * 下级下拉列表
     * @param obj
     * @returns {*|jQuery|HTMLElement}
     */
    sCity.prototype.fetchSub = function (obj) {
        var self = this;
        var subLevel = $(obj).attr("sublevel");
        if (subLevel) {
            var sub = self.config.root.children("." + subLevel);
            return sub;
        }
    }

    /**
     * 插入HTML
     */
    sCity.prototype.insertHtml = function () {
//            var box = $(config.box);
        var self = this;
        var tag = html;
        tag = tag.replace("$province", self.config.names.province);
        tag = tag.replace("$city", self.config.names.city);
        tag = tag.replace("$county", self.config.names.county);
        tag = tag.replace("$text", self.config.names.text);
        self.config.root.append(tag);

        self.obj = {}
        self.obj.province =self.config.root.children(".address_province");
        self.obj.city = self.config.root.children(".address_city");
        self.obj.county = self.config.root.children(".address_county");
        self.obj.text = self.config.root.children(".address_text");
    }

    /**
     * 绑定事件
     */
    sCity.prototype.bind = function () {
        var self = this;
//            $(".citySelect").each(function () {
        $.each(self.obj, function () {
            $(this).change(function () {
                var val = $(this).val();
                var obj = $(this);
                self.fillNext(obj, val);
                self.refreshText();
            });
        });
    }
    /**
     * 刷新文本
     */
    sCity.prototype.refreshText = function(){
        var self = this;
        var po = self.obj.province;
        var co = self.obj.city;
        var yo = self.obj.county;
        var txt = self.obj.text;
        var address = "";

        if(po.val() && po.val != ""){
            address += po.find("option:selected").text();
        }
        if(co.val() && co.val() != ""){
            address += co.find("option:selected").text();
        }
        if(yo.val() && yo.val != ""){
            address += yo.find("option:selected").text();
        }
        txt.val(address);
    }
    sCity.prototype.config = {};


    /**
     * 绑定全局控件
     * @param cfg
     * @returns {sCity}
     */
    $.selectCity = function (cfg) {
        cfg.root = $(cfg.box);
        var c = $.extend({}, config, cfg);
        var t = new sCity(c);
        return t;
    };

    $.fn.selectCity = function (cfg) {
        cfg.root = $(this);
        var c = $.extend({}, config, cfg);
        var t = new sCity(c);
        return t;
    };
})(jQuery);