Select2 不会格式化项目

Select2 won't format items

我不知道它是否与新库等有冲突,但我无法格式化 select 项。他们不会格式化为斜体和粗体。

http://jsfiddle.net/fcb960xh/2/

<select style="width: 300px">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
</select>

js

$(document).ready(function() {
    $('select').select2({
      // Specify format function for dropdown item
      formatResult: formatResult,
      // Specify format function for selected item
      formatSelection: formatSelection
    });
});

function formatResult(item) {
    if(!item.id) {
       return item.text;
    }
    // return item template
    return '<i style="color:#ff0000">' + item.text + '</i>';
}

function formatSelection(item) {
    // return selection template
    return '<b>' + item.text + '</b>';
}

您正在使用 select2 4.0.0。与以前的版本相比有所变化。

来自select2 4.0.0 announcements

Select2 previously provided multiple options for formatting the results list and selected options, commonly referred to as "formatters", using the formatSelection and formatResult options. As the "formatters" were also used for things such as localization, which has also changed, they have been renamed to templateSelection and templateResult and their signatures have changed as well.

您应该使用 templateResulttemplateSelection 而不是 formatResultformatSelection。您还应该 return 一个 jQuery 对象。这是更新后的 Fiddle.

我没有使用过 select2,但一个快速的方法可能只是向现有的样式添加样式 css class

.select2-results__group{
    font-style: italic
}

看看:https://jsfiddle.net/fcb960xh/9/