首页 文章

保留jquery select2下拉项中的选项类

提问于
浏览
0

有人知道是否可以将元素类转移到jquery select2下拉项?

<select>
  <option class="group-1"></option>
  <option class="group-1"></option>
  <option class="group-2"></option>
  <option class="group-2"></option>
</select>

我正在尝试基于用户's selected value from another dropdown, so if a user selects ' group 1 ' then I wish to only show the items with class ' group-1'构建动态列表 . 我希望能够做像 $('ul.select2 li.group-2').hide() 这样的事情 .

编辑:为了解决这个问题我已经开发的答案,我将这个问题分成2个问题,

1 回答

  • 1

    我设法通过使用select2 plugin的模板功能解决了这个问题,

    <script type="text/javascript">
    (function( $ ) {
      'use strict';
    
      var opportunities = $('select#opportunities').select2({
        dropdownParent: $('#select-opportunity'),
        templateResult: formatItem
      });
      function formatItem (state) {
        if (!state.id) { return state.text; }
        var $state = $(
          '<span class="opportunity-item ' + state.element.className + '">' + state.text + '</span>'
        );
        return $state;
      }
    })( jQuery );
    </script>
    

    注意:这不允许您操作select2下拉列表,因为class属性仅转移到项目的内部自定义 <span> 元素,而不是下拉select2列表的实际 <li> 元素 . 但是,进一步设置下拉列表的样式非常有用,例如,

    <style>
    .opportunity-item.group-1::after{
      content: '';
       display: inline-block;
       margin-left:5px;
       width: 10px;
       height: 10px;
       -moz-border-radius: 10px;
       -webkit-border-radius: 10px;
       border-radius: 10px;
       background-color: green;
    }
    .opportunity-item.group-2::after{
      content: '';
       display: inline-block;
       margin-left:5px;
       width: 10px;
       height: 10px;
       -moz-border-radius: 10px;
       -webkit-border-radius: 10px;
       border-radius: 10px;
       background-color: blue;
    }
    </style>
    

    导致,

    which makes for a nice visual distinction between different groups

相关问题