基于jquery的可查询多级select控件(可记录历史选择)

Posted phoebeyue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于jquery的可查询多级select控件(可记录历史选择)相关的知识,希望对你有一定的参考价值。

一、功能和使用

公司有功能需求,还要一条代码引入的控件,网上找完全符合的控件比较难,寻找所花的时间还不如自己写一个,所以找个空闲时间自己写了一个
 
控件功能:1、可手动输入查询,也可点击下拉框查询,
2、输入时实时定位到下拉框,enter补全
3、可多级查询(目前是写到二级)
4、localStorage存储历史记录
 
控件使用:引入相应的js和css文件,需要控件的html中加一个div
<div id="multiple_select" class="multiple-select-container"></div> 

js里引入控件

$("#multiple_select").multiSelect({
         type:‘2‘,//可选择几级数据
         data:data.list,
         field:[‘provence‘,‘city‘,‘name‘]  //option字段
  }); 

二、代码

HTML
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>树形控件</title>
    <link href="plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" /><!--bootstrap CSS-->
    <link rel="stylesheet" type="text/css" href="./multiSelect.css" />    
  </head>
  <body style="padding:100px;">  
      <div id="multiple_select" class="multiple-select-container"></div>     


  <script src="plugins/jquery-1.10.2.js"></script>
  <script src="plugins/bootstrap/js/bootstrap.min.js"></script>
  <script src="./multiSelect.js"></script>
  <script>
    $(function(){
      //测试用的数据
      var data = {
      list:[{
              provence:"湖北",
              city:[{name:"武汉",code:1}, {name:"仙桃",code:2},{name:"天门",code:3}]
          },          
            {
              provence:"河北",
              city:[{name:"石家庄",code:1}, {name:"邯郸",code:2},{name:"唐山",code:3}]
          },{
              provence:"湖南",
              city:[{name:"郴州",code:1}, {name:"岳阳",code:2},{name:"长沙",code:3}]
          }]          
      }
      //控件引用
      $("#multiple_select").multiSelect({
         type:‘2‘,//可选择几级数据
         data:data.list,
         field:[‘provence‘,‘city‘,‘name‘]  //option字段
      });
    });
  </script> 
  </body>
</html>

CSS

*{
	padding: 0;
	margin: 0;
}
ul li{
	list-style: none;
}
.multiple-select-container{
	width: 150px;
	height: 30px;
	position: relative;
}
.select-input{
	width: 100%;
	height: 100%;
	padding: 5px 14px 5px 5px;
	border: 1px solid #c2cad8;
	outline: none;
	border-radius: 3px;
}
.input-isfold{
	position: absolute;
	display: inline-block;
	left: calc(100% - 18px);
	top: 50%;
	transform: translateY(-50%);
	cursor: pointer;
}
.select-options-box{
	width:100%;
	display:none;
	position: absolute;
	border: 1px solid #c2cad8;
	z-index: 999999;
	background: #fff;
	height: 300px;
	overflow-y: auto;
}
.options-container{
	width: 100%;
	height: auto;
}
.options-record{
	font-size: 16px;
	width: 100%;
	height: 40px;
	box-sizing: border-box;
	line-height: 40px;
	padding: 0 5px;
	background: #EDEDED;
}
.options-one{
    font-size: 16px;
}
.options-two{
	width: 100%;
	font-size: 14px;
}
.options-two li{
	padding-left: 15px;
}
.optionslist{
	width: 100%;
	height: 40px;
	box-sizing: border-box;
	cursor: pointer;
	line-height: 40px;
	padding: 0 5px;
}
.optionslist:hover{
	background: #c2cad8;
}
.options-isfold{
	float: right;
	display: inline-block;
	width: 16px;
	line-height: 40px;
}
::-webkit-scrollbar{
	width: 5px;
	height: 5px;
}
::-webkit-scrollbar-thumb{
	background: #E5E5E5;
	border-radius: 3px;
}

JS

 ;(function($,window,document){

  var pluginName = ‘multiSelect‘,
    defaults = {
      type: ‘1‘,//select层级onetwo
      data:[],
      field:[],//数据字段名 
      record: true,  
      
      queryFun: function(){}
    };

  function MultiSelect(element,options){
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this.init();    
  }
  
  MultiSelect.prototype = { 

    //初始化弹出框
    init: function(){
      var that = this,
        element = this.element;

      that.create(element);      
      that.trigger(element);
    },
    
    //创建select框
    create: function(element){
      var that = this,
        $this = $(element),
        selectElement = ‘<input type="text" name="selectinput" id="select_input" class="select-input" placeholder="请选择" />‘
          +‘<span class="input-isfold glyphicon glyphicon-chevron-down"></span>‘
          +‘<div class="select-options-box" id="select_options_box"></div>‘;          
      $this.append(selectElement);  
      that.initOption();
    },
    //初始化列表
    initOption: function(){
      var that = this,
        $options_box = $(‘#select_options_box‘);
      var $options = that.parseOptions();        
      $options_box.html($options); 
    },
    //解析并处理options数据
    parseOptions: function(){
      var that = this,    
        type = that.settings.type,
        field = that.settings.field,
        one = field[0],
        two = field[1],
        data = that.settings.data,
        twolist = ‘‘,
        optionsTwo = [],
        recordColumn = that.settings.recordColumn,
        record = that.settings.record,
        options = ‘‘;   
      var recordColumn = JSON.parse(window.localStorage.getItem("recordInfo"))?JSON.parse(window.localStorage.getItem("recordInfo")):[];  
       console.log("recordColumn" +recordColumn);
      options += ‘<div class="options-container">‘;

      if (record && recordColumn.length > 0) {         
        for (var i = 0; i < recordColumn.length; i++) {
          twolist += ‘<li class="options-container optionslist">‘+‘-- ‘+‘<span class="options-data">‘+ recordColumn[i] +‘</span></li>‘;
        }
        options += ‘<div class="options-record">‘
                      +‘<span class="options-data">历史记录</span><span class="glyphicon glyphicon-chevron-up options-isfold"></span>‘
                  +‘</div>‘
                  +‘<ul class="options-two">‘+ twolist +‘</ul>‘;
      }
      switch(type){
        case ‘1‘:
          for (var i in data) {
            options+=‘<div class="optionslist"><span class="options-data">‘+data[i][one]+‘</span></div>‘;
          }
        case ‘2‘:
          for (var i in data) {
            twolist = ‘‘, optionsTwo = [];
            var optionsTwo = data[i][two];
            
            for (var j in optionsTwo){
              twolist+=‘<li class="options-container optionslist">‘+‘-- ‘+‘<span class="options-data">‘+ optionsTwo[j][field[2]] +‘</span></li>‘;
            }
            options+= ‘<div class="options-one optionslist">‘
                        +‘<span class="options-data">‘+ data[i][one] +‘</span><span class="glyphicon glyphicon-chevron-up options-isfold"></span>‘
                      +‘</div>‘
                      +‘<ul class="options-two">‘+ twolist +‘</ul>‘;
          }
      }
      options += ‘</div>‘;
      return options;     
    },

    //系列事件
    trigger: function(element,event){
      var that = this,
        $this = $(element),
        $options_box = $(‘#select_options_box‘),
        $isfold = $(‘.options-isfold‘),
        recordColumn = that.settings.recordColumn,
        record = that.settings.record,
        $input = $(‘#select_input‘);
      var recordColumn = JSON.parse(window.localStorage.getItem("recordInfo"))?JSON.parse(window.localStorage.getItem("recordInfo")):[]; 

      $input.on({
          ‘focus‘: function(){
            $options_box.fadeIn();  
            that.selectFun(false);
          },
          ‘input propertychange‘: function(){
            that.selectFun(false);
          },
          ‘click‘: function(){
            return false;
          }
      });
      $(‘.input-isfold‘).on(‘click‘, function(event){
        $options_box.toggle();
        $(this).toggleClass(‘glyphicon-chevron-down glyphicon-chevron-up‘);
        event.stopPropagation();
      })
      $isfold.on(‘click‘, function(event){
        $(this).parent().next().toggle();
        $(this).toggleClass(‘glyphicon-chevron-down glyphicon-chevron-up‘);
        $options_box.show();
        event.stopPropagation();
      })
      $(‘.optionslist‘).on({
        ‘click‘:function(event){
          $input.val($(this).find(‘.options-data‘).html());
          debugger
          if($.isFunction(that.settings.queryFun)){
              that.settings.queryFun();
          }
          if (record) {
            var recordCol = $input.val();
            // console.log("recordCol"+recordCol+"recordColumn" +recordColumn);
            if (JSON.stringify(recordColumn).indexOf(JSON.stringify(recordCol)) < 0){
              recordColumn.unshift(recordCol);
            }       
            window.localStorage.setItem("recordInfo", JSON.stringify(recordColumn));  
          }
          $options_box.fadeOut();
          event.stopPropagation();
        },
        ‘mouseover‘: function(){
          $(this).css({‘background‘:‘#c2cad8‘});
        },
        ‘mouseout‘ : function(){
          $(this).css({‘background‘:‘#fff‘});
        }       
      });

      $(document).keyup(function(event){        
        if(event.keyCode === 13){
          that.selectFun(true);
          if($.isFunction(that.settings.queryFun)){
            that.settings.queryFun();
          }
        }
        event.stopPropagation();
      });
      $(document).on(‘click‘, function(){
        $options_box.fadeOut();
      });
    },

    // input与select同步
    selectFun: function(enter){
      var that = this,
       $options_box = $(‘#select_options_box‘),
       $input = $(‘#select_input‘),
       optiondata = $input.val(),
       options = $(‘.optionslist‘),
       optionTop = 0,
       selectHTML = ‘‘;
      
       $.each(options, function(i, item){
          selectHTML = $(item).find(‘.options-data‘).html();
           // console.log(selected); 
          if(selectHTML.indexOf(optiondata) >= 0) { 
              // $(item).trigger(‘hover‘);
              options.css({‘background‘:‘#fff‘});
              $(item).css({‘background‘:‘#c2cad8‘});
              /*if ($(item).hasClass(‘options-one‘)) {
                optionTop = $(item).position().top;                                
              }else{
                optionTop = $(item).parent().position().top;
              }*/
              optionTop = $(item).position().top; 
              // console.log(optionTop);
              $options_box.scrollTop(optionTop);
              if (enter) {
                $(item).trigger(‘click‘);
              }
          } 
       });
       
       if (optiondata === ‘‘) {
          options.css({‘background‘:‘#fff‘});
          $options_box.scrollTop(0);
       } 
    }

  };

  $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new MultiSelect(this, options));     
          }
        });
    return this;
    };
  
 })(jQuery,window,document)

  

  

以上是关于基于jquery的可查询多级select控件(可记录历史选择)的主要内容,如果未能解决你的问题,请参考以下文章

JQUERY制作简洁的多级联动SELECT下拉框

cx选择是基于 jQuery公司的多级联动菜单插件,适用于省市、商品分类等联动菜单。

Select2 中的可选 optgroup

Selectize使用总结

如何在 C# 中拆分 OData 多级展开查询字符串?

基于Nginx+Lua改进多级缓存