jquery.cxselect.js 12.2 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
/*!
 * jQuery cxSelect
 * @name jquery.cxselect.js
 * @version 1.4.1
 * @date 2016-11-02
 * @author ciaoca
 * @email ciaoca@gmail.com
 * @site https://github.com/ciaoca/cxSelect
 * @license Released under the MIT license
 */
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else {
    factory(window.jQuery || window.Zepto || window.$);
  };
}(function($) {
  var cxSelect = function() {
    var self = this;
    var dom, settings, callback;

    // 分配参数
    for (var i = 0, l = arguments.length; i < l; i++) {
      if (cxSelect.isJquery(arguments[i]) || cxSelect.isZepto(arguments[i])) {
        dom = arguments[i];
      } else if (cxSelect.isElement(arguments[i])) {
        dom = $(arguments[i]);
      } else if (typeof arguments[i] === 'function') {
        callback = arguments[i];
      } else if (typeof arguments[i] === 'object') {
        settings = arguments[i];
      };
    };

    var api = new cxSelect.init(dom, settings);

    if (typeof callback === 'function') {
      callback(api);
    };

    return api;
  };

  cxSelect.isElement = function(o){
    if (o && (typeof HTMLElement === 'function' || typeof HTMLElement === 'object') && o instanceof HTMLElement) {
      return true;
    } else {
      return (o && o.nodeType && o.nodeType === 1) ? true : false;
    };
  };

  cxSelect.isJquery = function(o){
    return (o && o.length && (typeof jQuery === 'function' || typeof jQuery === 'object') && o instanceof jQuery) ? true : false;
  };

  cxSelect.isZepto = function(o){
    return (o && o.length && (typeof Zepto === 'function' || typeof Zepto === 'object') && Zepto.zepto.isZ(o)) ? true : false;
  };

  cxSelect.getIndex = function(n, required) {
    return required ? n : n - 1;
  };

  cxSelect.getData = function(data, space) {
    if (typeof space === 'string' && space.length) {
      space = space.split('.');
      for (var i = 0, l = space.length; i < l; i++) {
        data = data[space[i]];
      };
    };
    return data;
  };

  cxSelect.init = function(dom, settings) {
    var self = this;

    if (!cxSelect.isJquery(dom) && !cxSelect.isZepto(dom)) {return};

    var theSelect = {
      dom: {
        box: dom
      }
    };

    self.attach = cxSelect.attach.bind(theSelect);
    self.detach = cxSelect.detach.bind(theSelect);
    self.setOptions = cxSelect.setOptions.bind(theSelect);
    self.clear = cxSelect.clear.bind(theSelect);

    theSelect.changeEvent = function() {
      cxSelect.selectChange.call(theSelect, this.className);
    };

    theSelect.settings = $.extend({}, $.cxSelect.defaults, settings, {
      url: theSelect.dom.box.data('url'),
      emptyStyle: theSelect.dom.box.data('emptyStyle'),
      required: theSelect.dom.box.data('required'),
      firstTitle: theSelect.dom.box.data('firstTitle'),
      firstValue: theSelect.dom.box.data('firstValue'),
      jsonSpace: theSelect.dom.box.data('jsonSpace'),
      jsonName: theSelect.dom.box.data('jsonName'),
      jsonValue: theSelect.dom.box.data('jsonValue'),
      jsonSub: theSelect.dom.box.data('jsonSub')
    });

    var _dataSelects = theSelect.dom.box.data('selects');

    if (typeof _dataSelects === 'string' && _dataSelects.length) {
      theSelect.settings.selects = _dataSelects.split(',');
    };

    self.setOptions();
    self.attach();

    // 使用独立接口获取数据
    if (!theSelect.settings.url && !theSelect.settings.data) {
      cxSelect.start.apply(theSelect);

    // 设置自定义数据
    } else if ($.isArray(theSelect.settings.data)) {
      cxSelect.start.call(theSelect, theSelect.settings.data);

    // 设置 URL,通过 Ajax 获取数据
    } else if (typeof theSelect.settings.url === 'string' && theSelect.settings.url.length) {
      $.getJSON(theSelect.settings.url, function(json) {
        cxSelect.start.call(theSelect, json);
      });
    };
  };

  // 设置参数
  cxSelect.setOptions = function(opts) {
    var self = this;

    if (opts) {
      $.extend(self.settings, opts);
    };

    // 初次或重设选择器组
    if (!$.isArray(self.selectArray) || !self.selectArray.length || (opts && opts.selects)) {
      self.selectArray = [];

      if ($.isArray(self.settings.selects) && self.settings.selects.length) {
        var _tempSelect;

        for (var i = 0, l = self.settings.selects.length; i < l; i++) {
          _tempSelect = self.dom.box.find('select.' + self.settings.selects[i]);

          if (!_tempSelect || !_tempSelect.length) {break};

          self.selectArray.push(_tempSelect);
        };
      };
    };

    if (opts) {
      if (!$.isArray(opts.data) && typeof opts.url === 'string' && opts.url.length) {
        $.getJSON(self.settings.url, function(json) {
          cxSelect.start.call(self, json);
        });

      } else {
        cxSelect.start.call(self, opts.data);
      };
    };
  };

  // 绑定
  cxSelect.attach = function() {
    var self = this;

    if (!self.attachStatus) {
      self.dom.box.on('change', 'select', self.changeEvent);
    };

    if (typeof self.attachStatus === 'boolean') {
      cxSelect.start.call(self);
    };

    self.attachStatus = true;
  };

  // 移除绑定
  cxSelect.detach = function() {
    var self = this;
    self.dom.box.off('change', 'select', self.changeEvent);
    self.attachStatus = false;
  };

  // 清空选项
  cxSelect.clear = function(index) {
    var self = this;
    var _style = {
      display: '',
      visibility: ''
    };

    index = isNaN(index) ? 0 : index;

    // 清空后面的 select
    for (var i = index, l = self.selectArray.length; i < l; i++) {
      self.selectArray[i].empty().prop('disabled', true);

      if (self.settings.emptyStyle === 'none') {
        _style.display = 'none';
      } else if (self.settings.emptyStyle === 'hidden') {
        _style.visibility = 'hidden';
      };

      self.selectArray[i].css(_style);
    };
  };

  cxSelect.start = function(data) {
    var self = this;

    if ($.isArray(data)) {
      self.settings.data = cxSelect.getData(data, self.settings.jsonSpace);
    };

    if (!self.selectArray.length) {return};

    // 保存默认值
    for (var i = 0, l = self.selectArray.length; i < l; i++) {
      if (typeof self.selectArray[i].attr('data-value') !== 'string' && self.selectArray[i][0].options.length) {
        self.selectArray[i].attr('data-value', self.selectArray[i].val());
      };
    };

    if (self.settings.data || (typeof self.selectArray[0].data('url') === 'string' && self.selectArray[0].data('url').length)) {
      cxSelect.getOptionData.call(self, 0);
    } else {
      self.selectArray[0].prop('disabled', false).css({
        'display': '',
        'visibility': ''
      });
    };
  };

  // 获取选项数据
  cxSelect.getOptionData = function(index) {
    var self = this;

    if (typeof index !== 'number' || isNaN(index) || index < 0 || index >= self.selectArray.length) {return};

    var _indexPrev = index - 1;
    var _select = self.selectArray[index];
    var _selectData;
    var _valueIndex;
    var _dataUrl = _select.data('url');
    var _jsonSpace = typeof _select.data('jsonSpace') === 'undefined' ? self.settings.jsonSpace : _select.data('jsonSpace');
    var _query = {};
    var _queryName;
    var _selectName;
    var _selectValue;

    cxSelect.clear.call(self, index);

    // 使用独立接口
    if (typeof _dataUrl === 'string' && _dataUrl.length) {
      if (index > 0) {
        for (var i = 0, j = 1; i < index; i++, j++) {
          _queryName = self.selectArray[j].data('queryName');
          _selectName = self.selectArray[i].attr('name');
          _selectValue = self.selectArray[i].val();

          if (typeof _queryName === 'string' && _queryName.length) {
            _query[_queryName] = _selectValue;
          } else if (typeof _selectName === 'string' && _selectName.length) {
            _query[_selectName] = _selectValue;
          };
        };
      };

      $.getJSON(_dataUrl, _query, function(json) {
        _selectData = cxSelect.getData(json, _jsonSpace);

        cxSelect.buildOption.call(self, index, _selectData);
      });

    // 使用整合数据
    } else if (self.settings.data && typeof self.settings.data === 'object') {
      _selectData = self.settings.data;

      for (var i = 0; i < index; i++) {
        _valueIndex = cxSelect.getIndex(self.selectArray[i][0].selectedIndex, typeof self.selectArray[i].data('required') === 'boolean' ? self.selectArray[i].data('required') : self.settings.required);

        if (typeof _selectData[_valueIndex] === 'object' && $.isArray(_selectData[_valueIndex][self.settings.jsonSub]) && _selectData[_valueIndex][self.settings.jsonSub].length) {
          _selectData = _selectData[_valueIndex][self.settings.jsonSub];
        } else {
          _selectData = null;
          break;
        };
      };

      cxSelect.buildOption.call(self, index, _selectData);
    };
  };

  // 构建选项列表
  cxSelect.buildOption = function(index, data) {
    var self = this;

    var _select = self.selectArray[index];
    var _required = typeof _select.data('required') === 'boolean' ? _select.data('required') : self.settings.required;
    var _firstTitle = typeof _select.data('firstTitle') === 'undefined' ? self.settings.firstTitle : _select.data('firstTitle');
    var _firstValue = typeof _select.data('firstValue') === 'undefined' ? self.settings.firstValue : _select.data('firstValue');
    var _jsonName = typeof _select.data('jsonName') === 'undefined' ? self.settings.jsonName : _select.data('jsonName');
    var _jsonValue = typeof _select.data('jsonValue') === 'undefined' ? self.settings.jsonValue : _select.data('jsonValue');

    if (!$.isArray(data)) {return};

    var _html = !_required ? '<option value="' + String(_firstValue) + '">' + String(_firstTitle) + '</option>' : '';

    // 区分标题、值的数据
    if (typeof _jsonName === 'string' && _jsonName.length) {
      // 无值字段时使用标题作为值
      if (typeof _jsonValue !== 'string' || !_jsonValue.length) {
        _jsonValue = _jsonName;
      };

      for (var i = 0, l = data.length; i < l; i++) {
        _html += '<option value="' + String(data[i][_jsonValue]) + '">' + String(data[i][_jsonName]) + '</option>';
      };

    // 数组即为值的数据
    } else {
      for (var i = 0, l = data.length; i < l; i++) {
        _html += '<option value="' + String(data[i]) + '">' + String(data[i]) + '</option>';
      };
    };

    _select.html(_html).prop('disabled', false).css({
      'display': '',
      'visibility': ''
    });

    // 初次加载设置默认值
    if (typeof _select.attr('data-value') === 'string') {
      _select.val(String(_select.attr('data-value'))).removeAttr('data-value');

      if (_select[0].selectedIndex < 0) {
        _select[0].options[0].selected = true;
      };
    };

    if (_required || _select[0].selectedIndex > 0) {
      _select.trigger('change');
    };

  };

  // 改变选择时的处理
  cxSelect.selectChange = function(name) {
    var self = this;

    if (typeof name !== 'string' || !name.length) {return};

    var index;

    name = name.replace(/\s+/g, ',');
    name = ',' + name + ',';

    // 获取当前 select 位置
    for (var i = 0, l = self.selectArray.length; i < l; i++) {
      if (name.indexOf(',' + self.settings.selects[i] + ',') > -1) {
        index = i;
        break;
      };
    };

    if (typeof index === 'number' && index > -1) {
      index += 1;
      cxSelect.getOptionData.call(self, index);
    };
  };

  $.cxSelect = function() {
    return cxSelect.apply(this, arguments);
  };

  // 默认值
  $.cxSelect.defaults = {
    selects: [],            // 下拉选框组
    url: null,              // 列表数据文件路径(URL)或数组数据
    data: null,             // 自定义数据
    emptyStyle: null,       // 无数据状态显示方式
    required: false,        // 是否为必选
    firstTitle: '请选择',    // 第一个选项的标题
    firstValue: '',         // 第一个选项的值
    jsonSpace: '',          // 数据命名空间
    jsonName: 'n',          // 数据标题字段名称
    jsonValue: '',          // 数据值字段名称
    jsonSub: 's'            // 子集数据字段名称
  };

  $.fn.cxSelect = function(settings, callback) {
    this.each(function(i) {
      $.cxSelect(this, settings, callback);
    });
    return this;
  };
}));