Select2选项及说明

时间:2019-01-21 00:48:30

标签: jquery jquery-select2

我正在使用jQuery Select2作为选择框。我想为每个选项添加描述。打开选择框时,我看到以下文本:

One
Two
Three
Four

我想看:

One
*Description for option One*
Two
*Description for option Two*
Three
*Description for option Three*
Four
*Description for option Four*

有人知道我该怎么实现吗?

这是我的完整剧本:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script type="text/javascript">
  $.fn.select2.defaults = $.extend($.fn.select2.defaults, {
    allowClear: true,
    closeOnSelect: true,
    placeholder: 'Select...',
    minimumResultsForSearch: 15
  });

  $(document).ready(
    function () {
      var configParamsObj = {
        placeholder: '',
        minimumResultsForSearch: 3
      };

      $("#vat").select2(configParamsObj);
    }
  );
</script>

<select id="vat" name="vat">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
</select>

2 个答案:

答案 0 :(得分:0)

查看此答案:

Line Break in HTML Select Option?

摘要是,浏览器本身不支持下拉超过两行的下拉选项,我认为这是您想要的。作为安慰奖,您可以像这样将说明添加为工具提示吗?

<option value="1" title="*Description for option One*">One</option>

答案 1 :(得分:0)

一种方法可能是在每个可用选项下方使用disabled选项。此外,您可以使用templateResult插件的select2选项来自定义那些禁用选项的样式,如下例所示:

$.fn.select2.defaults = $.extend($.fn.select2.defaults,
{
    allowClear: true,
    closeOnSelect: true,
    placeholder: 'Select...',
    minimumResultsForSearch: 15
});

$(document).ready(function ()
{
    var configParamsObj = {
        placeholder: '',
        minimumResultsForSearch: 3,
        templateResult: function(data, container)
        {
            // Read and propagate the class attribute of elements.

            if (data.element)
                $(container).addClass($(data.element).attr("class"));

            return data.text;
        }
    };

    $("#vat").select2(configParamsObj);
});
.opt-desc
{
    font-size: 11px;
    color: skyblue !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select id="vat" name="vat" style="width:50%">
  <option value="1">One</option>
  <option class="opt-desc" disabled>Description of option One</option>
  <option value="2">Two</option>
  <option class="opt-desc" disabled>Description of option Two</option>
  <option value="3">Three</option>
  <option class="opt-desc" disabled>Description of option Three</option>
  <option value="4">Four</option>
  <option class="opt-desc" disabled>Description of option Four</option>
</select>