码迷,mamicode.com
首页 > Web开发 > 详细

js城市三级联动 ajax版

时间:2015-01-22 20:10:59      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:

写得乱七八糟:自己记录一下,不可使用!

(function (w, $) {
    //定义SelectSimulation的构造函数
    var SelectSimulation = function (ele, opt) {
        this.$element = ele,
        this.defaults = {
            ‘len‘: 3,
            ‘def‘: [],
            ‘ajax‘: [],
            ‘dataname‘: ‘data‘,
            ‘bind‘: [],//{ text: ‘text‘, val: ‘id‘ };
            ‘isnullstr‘: ‘无‘
        }
        this.options = $.extend({}, this.defaults, opt)
    }
    //定义SelectSimulation的方法
    SelectSimulation.prototype = {
        temp: function (str, obj) {
            return str.replace(/\{\$\w+\}/gi, function (matchs) {
                var returns = obj[matchs.replace(/\{\$/g, "").replace(/\}/g, "")];
                return (returns + "") == "undefined" ? "" : returns;
            });
        },
        Info: {
            tempstr: ‘ <div class="select-s-val"><a class="text-box"></a><input type="text" data-val="" readonly="readonly" /><a><i></i></a></div><div class="select-s-a"></div>‘,
            tempstra: ‘<a class="a-item" data-val="{$val}" data-text="{$text}">{$text}</a>‘,
            returndata: []
        },
        //main
        Init: function () {
            var _this = this;
            this.$element.html(this.Info.tempstr);
            if (_this.options.bind[0]) {
                _this.Info.tempstra = ‘<a class="a-item" data-val="{$‘ + _this.options.bind[0].val + ‘}" data-text="{$‘ + _this.options.bind[0].text + ‘}">{$‘ + _this.options.bind[0].text + ‘}</a>‘;
            }
            if (this.options.def[0] == ‘undefined‘ && this.options.def.length === this.options.len) {
                for (var i = 0, j = this.options.len; i < j; i++) {
                    this.options.def.push({ text: ‘--请选择--‘, val: ‘-1‘ });
                }
            }
            else {
                //alert(‘不能正确执行‘);
                //return false;
            }
            //初始化第一个容器
            this.Finddata(this.options.ajax[0].url, this.options.ajax[0].data, function (data) {
                //console.log(JSON.stringify(data));

                var htmlstr = this.Binddata(data[this.options.dataname]);
                var $element0 = this.$element.eq(0);
                $element0.attr("data-type", ‘0‘);
                $element0.find("div.select-s-a").html(htmlstr);
                var $element_input = $element0.find("input");
                var $alist = $element0.find("a.a-item");
                $alist.click(function () {
                    $element_input.val($(this).attr(‘data-text‘));
                    $element_input.attr(‘data-val‘, $(this).attr(‘data-val‘));
                    _this.Changedata.call(_this, (parseInt($element0.attr(‘data-type‘)) + 1), $(this).attr(‘data-val‘));
                    $(this).parent().hide();
                });
            });

            this.Bindfocus();
            return this.Info.returndata;
        },
        //联动
        Changedata: function (item, val) {
            var _this = this;
            if (item >= this.options.len) {
                return;
            }
            this.options.ajax[item].data[this.options.ajax[item].data[‘def‘]] = val;
            this.Finddata(this.options.ajax[item].url, this.options.ajax[item].data, function (data) {
                //console.log(JSON.stringify(data));
                var htmlstr = this.Binddata(data[this.options.dataname]);
                var $element0 = this.$element.eq(item);
                $element0.attr("data-type", item);
                $element0.find("div.select-s-a").html(htmlstr);
                var $element_input = $element0.find("input");
                var $alist = $element0.find("a.a-item");
                $alist.click(function () {
                    $element_input.val($(this).attr(‘data-text‘));
                    $element_input.attr(‘data-val‘, $(this).attr(‘data-val‘));
                    _this.Changedata.call(_this, (parseInt($element0.attr(‘data-type‘)) + 1), $(this).attr(‘data-val‘));
                    $(this).parent().hide();
                });

                if ($alist.length > 0) {
                    $element_input.val($alist.eq(0).attr(‘data-text‘));
                    $element_input.attr(‘data-val‘, $alist.eq(0).attr(‘data-val‘));
                    _this.Changedata.call(_this, (parseInt($element0.attr(‘data-type‘)) + 1), $alist.eq(0).attr(‘data-val‘));
                }
                else {
                    $element_input.val(_this.options.isnullstr[item] ? _this.options.isnullstr[item] : _this.options.isnullstr);
                    $element_input.attr(‘data-val‘, ‘‘);
                }
            });
        },
        //数据处理
        Binddata: function (data) {
            if (data == null) return ‘‘;
            var _this = this;
            var _strall = ‘‘;
            for (var i = 0, j = data.length; i < j; i++) {
                _strall += _this.temp(_this.Info.tempstra, data[i]);
            }
            return _strall;
        },
        //通过ajax调数据
        Finddata: function (url, data, fn) {
            var _this = this;
            $.ajax({
                url: url,
                type: "get",
                data: data,
                dataType: "json",
                cache: false, //禁止缓存
                success: function (obj) {
                    fn.call(_this, obj);
                }
            });
        },
        //模拟系统焦点事件
        Bindfocus: function () {
            var _this = this;
            this.$element.attr(‘tabindex‘, ‘1‘);
            var _isoftrue = [];
            this.$element.each(function (item) {
                var $element_input = $(this).find("input");
                $element_input.val(_this.options.def[item].text);
                $element_input.attr(‘data-val‘, _this.options.def[item].val);
                _isoftrue.push(false);
            });
            this.$element.click(function (event) {
                event.preventDefault();
                event.stopPropagation();
                var _$this = $(this);
                var _$selecta = _$this.find("div.select-s-a");
                var _$selectval = _$this.find("div.select-s-val");
                if (_$selecta.css(‘display‘) === ‘none‘) {
                    _$selectval.removeClass(‘focuss‘).addClass(‘focuss‘);
                    _$selecta.show();
                }
                else {
                    _$selectval.removeClass(‘focuss‘);
                    _$selecta.hide();
                }
            }).hover(function () {
                _isoftrue[$(this).index()] = true;
            }, function () {
                _isoftrue[$(this).index()] = false;
            });
            this.$element.focusout(function () {
                //alert($(this).index()+‘,‘+_isoftrue[$(this).index()]);
                if (_isoftrue[$(this).index()]) return;
                var _$this = $(this);
                var _$selecta = _$this.find("div.select-s-a");
                var _$selectval = _$this.find("div.select-s-val");
                _$selectval.removeClass(‘focuss‘);
                _$selecta.hide();
            });
            this.$element.find("div.select-s-a").click(function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        getText: function () {
            var valuedata = [];
            this.$element.each(function () {
                var $element_input = $(this).find("input");
                valuedata.push($element_input.val());
            });
            return valuedata;
        },
        getValues: function () {
            var valuedata = [];
            this.$element.each(function () {
                var $element_input = $(this).find("input");
                valuedata.push($element_input.attr(‘data-val‘));
            });
            return valuedata;
        }
    }
    //在插件中使用SelectSimulation对象
    $.fn.MySelect = function (options) {
        //创建SelectSimulation的实体
        var _CselectSimulation = new SelectSimulation(this, options);
        if (typeof options != ‘object‘ && options != undefined) {
            return _CselectSimulation[options]();
        }
        else {
            _CselectSimulation.Init();
        }
    }
})(window, $);

  

  //地区显示
    $("div.select-simulation").MySelect({
        ‘len‘: 3,
        ‘def‘: [{ text: ‘--请选择省份‘, val: -1 }, { text: ‘--请选择城市‘, val: -1 }, { text: ‘--请选择区/县‘, val: -1 }],
        ‘ajax‘: [{ url: ‘GetArea‘, data: { parentID: 0 } }, { url: ‘GetArea‘, data: { def: ‘parentID‘ } }, { url: ‘GetArea‘, data: { def: ‘parentID‘ } }],
        ‘bind‘: [{ text: ‘AreaName‘, val: ‘AreaID‘ }, { text: ‘AreaName‘, val: ‘AreaID‘ }, { text: ‘AreaName‘, val: ‘AreaID‘ }],
        ‘isnullstr‘: [‘无省份‘, ‘无城市‘, ‘无区/县‘]
    });
    $("#hudezi").click(function () {
        alert($("div.select-simulation").MySelect(‘getValues‘)[0]);
        alert($("div.select-simulation").MySelect(‘getValues‘)[1]);
        alert($("div.select-simulation").MySelect(‘getValues‘)[2]);

        alert($("div.select-simulation").MySelect(‘getText‘)[0]);
        alert($("div.select-simulation").MySelect(‘getText‘)[1]);
        alert($("div.select-simulation").MySelect(‘getText‘)[2]);

    });

css

.select-simulation { position: relative; height: 25px; width: 177px; z-index: 1; display: inline-block; *display: block; *zoom: 1; *display: inline; font-size: 12px; color: 666; outline: none;vertical-align:middle; }
.select-simulation .select-s-val { border: 1px solid #d0d2d9; *zoom: 1; position: relative; z-index: 5; top: 0px; left: 0px; *zoom: 1; }
.select-simulation .select-s-val.focuss { border-color: #0094ff; }
.select-simulation .select-s-val:hover { border-color: #0094ff; }
.select-simulation .select-s-val:after { content: "clear"; height: 0px; display: block; overflow: 0px; visibility: hidden; clear: both; }
.select-simulation .select-s-val .text-box { display: inline-block; width: 154px; border: none; height: 25px; background: #fff; filter: alpha(opacity=0); opacity: 0; position: absolute; left: 0px; top: 0px; z-index: 1; }
.select-simulation .select-s-val input { width: 144px; float: left; outline: none; border: 0px; height: 25px; line-height: 20px;padding:0px; padding-left: 5px; }
.select-simulation .select-s-val a { width: 25px; height: 25px; float: left; background: #fff; border-left: 1px solid #e2e2e2; cursor: default; }
.select-simulation .select-s-val a i { display: block; width: 0px; height: 0px; border: 5px dashed transparent; border-top: 5px solid #888; overflow: hidden; float: left; margin: 10px 0px 0px 8px; _display: inline; }
/*.select-simulation .select-s-val a:hover { background: #888; }
        .select-simulation .select-s-val a:hover i { border-top-color: #ddd; }*/

.select-simulation .select-s-a { position: absolute; top: 26px; left: 0px; width: 175px; border: 1px solid #e2e2e2; height: 175px; overflow: auto; display: none; z-index: 3;background:#fff; }
.select-simulation .select-s-a a { display: block; height: 20px; text-align: left; text-indent: 5px; line-height: 20px; overflow: hidden; cursor: default; }
.select-simulation .select-s-a a:hover { background: #2793fb; color: #fff; }

  

  

html

 <span>地    区:</span>
            <span> 省:</span><div class="select-simulation"></div>
            <span> 市:</span><div class="select-simulation"></div>
            <span> 区/县:</span><div class="select-simulation"></div>

  

js城市三级联动 ajax版

标签:

原文地址:http://www.cnblogs.com/yc-code/p/4242423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!