根据JSON自动生成select联动

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012081441/article/details/88536212

公用js


  var CreateSelect = function (obj) {
    this.__ID__ = 0;
    this.$dom = $(obj.dom);
    this.selectList = obj.data;
    this.onChange = obj.onChange;
    this.init();
  }

  CreateSelect.prototype = {
    // 初始化
    init() {
      this.initData();
      this.initCreateBox();
      this.bindEvent();
    },
    // 给每个item赋一个id,方便后面查找
    initData: function () {
      var list = this.selectList.list;
      var id = 0;
      var bindId = function (_list) {
        _list.map(item => {
          item.__ID__ = id++;
          if (item.childs) {
            bindId(item.childs.list);
          }
        });
      }
      bindId(list);
    },
    // 返回一个option结构(列表)
    createOption: function (arr, _value) {
      console.log(_value)
      var option = function (obj) {
        var selected = _value && obj.value == _value ? 'selected' : '';
        return '<option value="' + obj.value + '" data-id="' + obj.id + '" ' + selected + ' >' + obj.text + '</option>'
      };
      var options = '';
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        var text = item.text;
        var value = item.value || text;
        var id = item.__ID__;
        options += option({
          text: item.text,
          value: value,
          id: id
        });
      }
      return options;
    },
    createBox(node, label = "") {
      return '<div class="create-select"> <div class="create-select-label">' + label + '</div> ' + node + '</div>'
    },
    // 返回一个Select+Option的结构
    createSelect: function (arr, label, value) {
      var select = (optionNode) => {
        let id = this.__ID__++;
        return '<select data-id="' + id + '">' + optionNode + '</select>'
      };
      var options = this.createOption(arr, value);
      return this.createBox(select(options), label);
    },
    // 初始化创建Select
    initCreateBox(valueArr) {

      $dom = this.$dom;
      var data = this.selectList;
      var selects = '';
      let index = 0;

      var createSelect = (data) => {


        var childs = data.list[0].childs;
        var selectValue = '';
        if (valueArr && valueArr[index]) {
          var valueItem = this.getItemByValue(valueArr[index].value, data.list);
          if (valueItem) {
            childs = valueItem.childs;
            selectValue = valueItem.value;
          }

        }
        var select = this.createSelect(data.list, data.label, selectValue);
        selects += select;
        index++;

        if (childs) {
          createSelect(childs);
        }
      }
      createSelect(data);
      $dom.html(selects);
    },
    // 刷新后面的options
    reloadOptions(id) {
      $box = this.$dom;
      let item = this.getItemById(id);
      let createRight = (item) => {
        let childs = item.childs;
        if (childs) {
          $box.append(this.createSelect(childs.list, childs.label));
          let firstChilds = childs.list[0].childs;
          if (firstChilds) {
            $box.append(this.createSelect(firstChilds.list, firstChilds.label));
            createRight(firstChilds.list);
          }
        }
      };
      createRight(item);
    },
    // 根据value查找传入list的item;
    getItemByValue(value, list) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].value == value) {
          return list[i]
        }
      }
      return null;
    },
    // 根据id获取item
    getItemById(id) {
      var list = this.selectList.list;

      var getId = function (_list) {
        for (let i = 0; i < _list.length; i++) {
          let item = _list[i];

          if (item.__ID__ == id) {
            return item;
          }

          if (item.childs) {
            let idItem = getId(item.childs.list);
            if (idItem) {
              return idItem
            }
          }
        };
        return null;
      };
      let itemById = getId(list);
      return itemById;
    },
    // 获取values
    getValue() {
      let arr = [];
      let that = this;
      this.$dom.find('select option:selected').each(function () {
        let id = $(this).data('id');
        let item = that.getItemById(id);
        arr.push(item)
      });
      return arr;
    },
    setValue(arr) {
      console.log('go')
      this.initCreateBox(arr);
    },
    // 绑定事件
    bindEvent: function () {
      var that = this;
      this.$dom.on('change', 'select', function () {
        var $selectedOption = $(this).find('option:selected');
        var id = $selectedOption.data('id');
        var selectId = $(this).data('id');
        that.$dom.find('select[data-id="' + selectId + '"]').parents('.create-select').find('~.create-select').remove();
        that.reloadOptions(id);
        that.onChange && that.onChange(that.getValue());
      });
    }
  };

html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="jquery.js"></script>
  <script src="createSelect.js"></script>
  <title>createSelect</title>
  <style type="text/css">
  	.create-select {
	  display: flex;
	  align-items: center;
	  margin: 10px 0;
	}
	
	.create-select .create-select-label {
	  color: #666;
	  width: 100px;
	  text-align: right;
	  margin-right: 10px;
	}
	
	.create-select select {
	  height: 30px;
	  padding: 0 10px;
	  min-width: 120px;
	}
  </style>
</head>

<body>
  <div id="test">
  </div>
  <script>
    var select = new CreateSelect({
      dom: '#test',
      data: {
        label: '客户分类',
        list: [{
          text: '起亚客户',
          value: '0',
          childs: {
            label: '制作费用',
            list: [{
              text: '标准合同',
              value: '0',
              childs: {
                label: '类型',
                list: [{
                  text: '灯箱广告',
                  value: '0'
                }, {
                  text: '电梯看板',
                  value: '1'
                }, {
                  text: '驾校',
                  value: '2'
                }, {
                  text: '楼宇液晶',
                  value: '3'
                }]
              }
            }, {
              text: '含制作费',
              value: '1',
              childs: {
                label: '类型',
                list: [{
                  text: '灯箱广告',
                  value: '0'
                }, {
                  text: '电梯看板',
                  value: '1'
                }, {
                  text: '驾校',
                  value: '2'
                }]
              }
            }]
          }
        }, {
          text: '非起亚客户',
          value: '1',
          childs: {
            label: '制作费用',
            list: [{
              text: '电台',
              value: '0'
            }, {
              text: '楼宇液晶',
              value: '1'
            }, {
              text: '纸媒',
              value: '2'
            }, {
              text: '桌贴',
              value: '3'
            }]
          }
        }]
      },
      onChange(arr) {
        console.log(arr)
      }
    });
    //获取下拉组合的的集合
		function getSelectValue(){
			if(!select){
				return '';
			}
		   var arr = select.getValue();
		   var a = [];
		   arr.map(item => {
			   a.push(item.value);
		   });
		   return a.join('_');
		}
		//获取下拉组合的的文本
		function getSelectValueTest(){
			if(!select){
				return '';
			}
		   var arr = select.getValue();
		   var a = [];
		   arr.map(item => {
			   a.push(item.text);
		   });
		   return a.join('-');
		}
		console.log("getSelectValue=="+getSelectValue());
		console.log("getSelectValue=="+getSelectValueTest());
  </script>
</body>

</html>

插件下载地址

猜你喜欢

转载自blog.csdn.net/u012081441/article/details/88536212