mutil_select.js 15.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
/**
 * 多级分类,多项选择插件
 * @author ln
 * 插件使用 
    #html 说明

    1、数据类型为多级商品分类    
    <div class="mutil-select" dataSource="cate" level="2" dataUrl="http://shop.nong12.com/shop/common/jsonpCategory"></div>
    2、省市地多级联动
    <div class="mutil-select" dataSource="region" level="3" dataUrl="http://manweb.nong12.com/city/getCountryJsonpList.do"></div>
    3、普通下拉选项框
    <div class="mutil-select" dataSource="default" level="1" source='[{"id":"","name":"请选择"},{"id":"1","name":"测试"}]'></div>
    
    #css样式
    .mutil-select .selects-group{display:inline-block}
    .mutil-select .btn-add{display:inline-block;width:43px;height:30px;line-height:30px;background:#23ac38;color:#fff;text-align:center;border:1px #23ac38 solid;cursor:pointer;font-size:13px;border-radius:4px}
    .mutil-select .btn-add:hover{filter:alpha(opacity=80);opacity:.8}
    .mutil-select select{padding:8px 0;line-height:30px;min-width:140px;margin-right:20px}
    .mutil-select .invalid{border:1px solid #f60}
    .mutil-select .rs-box{display:inline-block;background:#eee;margin-top:10px}
    .mutil-select .rs-box .item{display:inline-block;color:#666;min-width:100px;padding-right:20px;margin:10px;background:#fff;text-indent:8px;border:1px solid #ddd;position:relative}
    .mutil-select .rs-box .icon-close{display:inline-block;width:14px;height:14px;vertical-align:middle;position:absolute;right:8px;top:50%;margin-top:-7px;background:url(../images/close.png) center center no-repeat;cursor:pointer}
    .mutil-select .rs-box .icon-close:hover{background:url(../images/closeh.png) center center no-repeat}
    
    #seajs 调用方式
    seajs.use(['../js/javascript/mutil_select/mutil_select.js'],function(mutilSelect){
        
        $(".mutil-select").each(function(index, el) {
            var dataSource = $(el).attr('dataSource');
            var level = $(el).attr('level');
            var source = $(el).attr('source');
            var dataUrl = $(el).attr('dataUrl');

            if(dataSource){
                new mutilSelect($(el),{
                    // 实例化的数据类型
                    dataSource:dataSource, 
                    // 多级联动最大级别
                    level:Number(level),
                    // 默认数据类型时传入JSON对象数组
                    source:source,
                    // 远程数据加载url
                    dataUrl:dataUrl,
                    // 数据更新回掉方法
                    callback:function(data){
                        console.log(data);
                    }
                });
            }
        });
    });
 */
define(function(require, exports, module) {

    var tpl = '<div class="selects-group">' +
        '</div>' +
        '<a href="" class="btn-add">添加</a>' +
        '<div class="clearfix"></div>' +
        '<div class="rs-box">' +
        '</div>';

    function indexOf(item,array){
        for (var i = 0; i < array.length; i++) {
            if(array[i] == item) return i;
        }
        return -1;
    }
    /**
     * 获取数据资源,返回数据统一使用 {key:value}
     * @type {Object}
     */
    var dataSource = {
        // 根据 {} 数据对象初始化
        "default": function(pid, records_ids, select_index, cb) {
            if(typeof this.opt.source === "string"){
                this.opt.source = $.parseJSON(this.opt.source);
            }
            var default_labels = this.opt.default_labels;
            var data = this.opt.source;
            var hash = [];
            var idField = this.opt.map['id'] || "id";
            var nameField = this.opt.map['name'] || "name";

            if (default_labels[select_index]) {
                hash.push({
                    id: "",
                    name: default_labels[select_index]
                });
            }
            $.each(data, function(index, one) {
                if (indexOf(one[idField], records_ids) === -1) {
                    hash.push({
                        id: one[idField],
                        name: one[nameField]
                    });
                }
            });
            return cb(hash);
        },
        
        // 通用远程数据源
        common: function(pid, records_ids, select_index, cb) {
            var default_labels = this.opt.default_labels;
            var idField = this.opt.map['id'] || "id";
            var nameField = this.opt.map['name'] || "name";
            var pIdField = this.opt.map['pid'] || "pid";

            $.ajax({
                url: this.opt.dataUrl + "?" + pIdField + "=" + pid,
                dataType: "jsonp",
                success: function(data) {
                    var hash = [];
                    if (default_labels[select_index]) {
                        hash.push({
                            id: "",
                            name: default_labels[select_index]
                        });
                    }
                    $.each(data, function(index, one) {
                        if (indexOf(one[idField], records_ids) === -1) {
                            hash.push({
                                id: one[idField],
                                name: one[nameField]
                            });
                        }
                    });
                    return cb(hash);
                },
                error: function(e) {}
            });
        },
        cate: function(pid, records_ids, select_index, cb) {
            var default_labels = this.opt.default_labels;
            var idField = this.opt.map['id'] || "cid";
            var nameField = this.opt.map['name'] || "cname";
            var pIdField = this.opt.map['pid'] || "pid";

            $.ajax({
                url: this.opt.dataUrl + "?" + pIdField + "=" + pid,
                dataType: "jsonp",
                success: function(data) {
                    if(!data || data.length === 0){
                        return cb([]);
                    }
                    var hash = [];
                    if (default_labels[select_index]) {
                        hash.push({
                            id: "",
                            name: default_labels[select_index]
                        });
                    }
                    $.each(data, function(index, one) {
                        if (indexOf(one[idField], records_ids) === -1) {
                            hash.push({
                                id: one[idField],
                                name: one[nameField]
                            });
                        }
                    });
                    return cb(hash);
                },
                error: function(e) {}
            });
        },

        /**
         * 地区
         */
        region: function(pid, records_ids, select_index, cb) {
            var default_labels = this.opt.default_labels;
            var idField = this.opt.map['id'] || "regionId";
            var pIdField = this.opt.map['pid'] || "pid";
            var nameField = this.opt.map['name'] || "regionName";

            $.ajax({
                url: this.opt.dataUrl + "?"+pIdField+"=" + pid,
                dataType: "jsonp",
                success: function(data) {
                    if(!data || data.length === 0){
                        return cb([]);
                    }
                    var hash = [];
                    if (default_labels[select_index]) {
                        hash.push({
                            id: "",
                            name: default_labels[select_index]
                        });
                    }
                    $.each(data, function(index, one) {
                        if (indexOf(one[idField], records_ids) === -1) {
                            hash.push({
                                id: one[idField],
                                name: one[nameField]
                            });
                        }
                    });
                    return cb(hash);
                },
                error: function(e) {}
            });
        }
    };

    function mutilSelect($container, options) {
        this.$container = $container;
        this.records = [];
        this.records_ids = [];

        // 可选项
        this.opt = {
            level: 1,
            // 数据url
            dataUrl: "",
            //  cate 品类  region 区域  直接传一个对象 {} 就按照单独的方式处理
            dataSource: "cate",
            // 拓展数据源 参考 dataSource 对象写法
            dataSourceFn: {},
            // default 类型时直接传入字面量
            source: '[{"id":"","name":"请选择"}]',
            // 数数据发生变化
            callback: function() {},
            // 数据源字段映射, 例如 {id:"regionId"}
            map: {

            },
            // 父级ID
            pid:0,
            inputName: "mutil_select" + Math.round(Math.random() * 100),
            // 已经选中的数据 [{id:xx,name:xx}]
            records:[],
            // 已经选中的数据 []
            records_ids:[],
            // 默认标签
            default_labels:{
                0: "请选择",
                1: "请选择",
                2: "请选择",
                3: "请选择",
                4: "请选择"
            },
            // 输出排序 asc 正序,desc 逆序
            rs_sort:"asc"
        };

        if (typeof dataSource[this.opt.dataSource] === "undefined") {
            return;
        }
        $.extend(this.opt, options);
        // 拓展数据源
        $.extend(dataSource, this.opt.dataSourceFn);

        this.Init();
    }

    mutilSelect.prototype = {
        isInit: false,
        Init: function() {
            var that = this;
            this.$container.html(tpl);
            this.$selects_group = this.$container.find(".selects-group");
            this.$rs_box = this.$container.find(".rs-box");

            var idField = this.opt.map['id'] || "id";
            var nameField = this.opt.map['name'] || "name";
            if(this.opt.records.length){
                if(typeof this.opt.records === "string"){
                    this.opt.records = $.parseJSON(this.opt.records);
                }
                $.each(this.opt.records,function(index,one) {
                    that.records.push({id:one[idField],name:one[nameField]});
                    that.records_ids.push(one[idField]);
                });
            }else if(this.opt.records_ids.length && this.opt.level == 1){
                dataSource[this.opt.dataSource].call(this, 0, [], 0, $.proxy(function(data) {
                    if(!data)
                        return ;

                    $.each(this.opt.records_ids,function(index,id) {
                        // 从 source 中找到name
                        var name = "";
                        $.each(data,function(index, source_one) {
                            if(source_one.id == id){
                                name = source_one.name
                                return false;
                            }
                        });
                        that.records.push({id:id,name:name});
                        that.records_ids.push(id);
                    });
                    this.renderRs();
                }, this));
            }

            this.renderSelect(this.opt.pid, 0);
            this.renderRs();
            this.bindEvent();
        },

        // 绑定事件
        // 如果一个select change 需要移除后面的select 然后重建后后面的select
        bindEvent: function() {
            var that = this;

            this.$container.on('change', 'select', function(event) {
                event.preventDefault();
                var has_next = $(this).next();
                var index = $(this).index();
                var value = $(this).val();
                $(this).removeClass('invalid');
                if (!value || !has_next || (index + 1) >= that.opt.level) {
                    that.$selects_group.children(':gt(' + index + ')').remove();
                    return;
                }
                that.renderSelect(value, index + 1);
            });

            this.$container.on('click', '.btn-add', function(event) {
                event.preventDefault();
                var $last = that.$selects_group.children(':last');
                var value = $last.val();
                var $option = $last.find('[value="' + value + '"]');
                var name = $option.text();
                if (!value) {
                    $last.addClass('invalid');
                    return;
                }
                that.records.push({
                    id: value,
                    name: name
                });
                that.records_ids.push(value);

                that.lastSelectRefresh();
                that.updateData();
                that.renderRs();
                return false;
            });

            this.$container.on('click', '.icon-close', function(event) {
                event.preventDefault();
                var id = $(this).attr('data-id');
                $.each(that.records, function(index, one) {
                    if (!one) {
                        return;
                    }
                    if (one.id == id) {
                        that.records.splice(index, 1);
                        that.records_ids.splice(index, 1);
                    }
                });

                that.lastSelectRefresh();
                that.updateData();
                that.renderRs();
                return false;
            });
        },
        renderSelect: function(pid, index) {
            dataSource[this.opt.dataSource].call(this, pid, this.records_ids, index, $.proxy(function(data) {
                if (typeof index !== "undefined") {
                    var current_index = !index ? 0 : index - 1;
                    this.$selects_group.children(':gt(' + current_index + ')').remove();
                }
                if (data.length < 1) {
                    return;
                }
                var $select = $('<select pid="' + pid + '" index="' + index + '">');
                var options = [];
                $.each(data, function(key, value) {
                    options.push('<option value="' + value.id + '">' + value.name + '</option>');
                });
                $select.html(options.join(""));
                this.$selects_group.append($select);

                this.$container.trigger('renderSelectEnd');
            }, this));
        },
        // 刷新最后一个select 内容
        lastSelectRefresh: function() {
            var $last = this.$selects_group.children(':last');
            var pid = $last.attr('pid');
            var index = $last.attr('index');

            dataSource[this.opt.dataSource].call(this, pid, this.records_ids, index, $.proxy(function(data) {
                var options = [];
                $.each(data, function(key, value) {
                    options.push('<option value="' + value.id + '">' + value.name + '</option>');
                });
                $last.html(options.join(""));
            }, this));
        },
        renderRs: function() {
            var that = this;
            var items = [];
            var records = this.records.slice();
            if(this.opt.rs_sort == "desc"){
                records.reverse();
            }
            $.each(records, function(index, one) {
                items.push('<div class="item">' + one.name + '<i class="m-icon icon-close" data-id="' + 
                    one.id + '"></i>'+'<input type="hidden" name="'+that.opt.inputName+'" value="'+one.id+'" />'+
                    '</div>');
            });
            this.$rs_box.html(items.join(""));
        },
        updateData: function() {
            if (typeof this.opt.callback === "function") {
                this.opt.callback(this.records);
            }
        }
    };

    return mutilSelect;
});