如何在 select2 选项中呈现 html

How to render html in select2 options

在从远程源加载的 this example 数据中,我可以看到图像和其他 html 元素呈现为选项。我想使用本地数组中的数据完成同样的事情。我已经尝试按照文档中的描述构建一个数组,并使用 data 选项添加它,但是 html 呈现为纯文本:

var data = [
  { id: 0, text: '<div style="color:green">enhancement</div>' },
  { id: 1, text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>' }];

$("select").select2({
  data: data
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select></select>

如何向 select2 选项添加 html 内容?

如果我没记错的话,如果您设置了 templateResult 和 templateSelection 选项并让它们 return 一个 jQuery 对象,那么您只能渲染 HTML。

var data = [
      { id: 0, text: '<div style="color:green">enhancement</div>' },
      { id: 1, text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>' }];

    $("select").select2({
      data: data,
      templateResult: function (d) { return $(d.text); },
      templateSelection: function (d) { return $(d.text); },
      
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

    <select></select>
 

好的,玩了一会儿,找到了一个可行的解决方案,所以我会在这里回答我自己的问题。

对我来说,这里的关键是构建一个包含 templateSelectiontemplateResult 内容的数据数组。后者在下拉列表中呈现良好,但任何多行内容都不会包含在 select2 元素中,因此需要内联显示(或至少在单行上)。将 escapeMarkup 定义为选项允许覆盖通常会删除 html 内容的核心功能。

定义 title 属性也很重要,否则您将在工具提示中得到 html 标记。

var data = [{
  id: 0,
  text: '<div style="color:green">enhancement</div>',
  html: '<div style="color:green">enhancement</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
  title: 'enchancement'
}, {
  id: 1,
  text: '<div style="color:red">bug</div>',
  html: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>',
  title: 'bug'
}];

$("select").select2({
  data: data,
  escapeMarkup: function(markup) {
    return markup;
  },
  templateResult: function(data) {
    return data.html;
  },
  templateSelection: function(data) {
    return data.text;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select></select>

或者,通过一些小的 CSS 调整,您可以允许完整的 html 选项内容显示在 select 容器内,而不需要模板回调:

var data = [{
  id: 0,
  text: '<div style="font-size: 1.2em; color:green">enhancement</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
  title: 'enchancement'
}, {
  id: 1,
  text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>',
  title: 'bug'
}];

$("select").select2({
  data: data,
  escapeMarkup: function(markup) {
    return markup;
  }
})
.select2-container .select2-selection--single {
  height: auto!important;
  padding: 5px 0;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
  line-height: normal!important;
}
.select2-container .select2-selection--single .select2-selection__rendered {
  white-space: normal!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select style="width: 100%"></select>

您只需将另一个带有 html 的字段添加到您的数据数组,然后使用 templateResult 选项制作您自己的模板,就像这样

JSFiddle Demo

var data = [{
   id: 0,
   text: 'enhancement',
   html: '<div style="color:green">enhancement</div>'
}, {
   id: 1,
   text: 'bug',
   html: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>'
}];

function template(data) {
    return data.html;
}

$("select").select2({
   data: data,
   templateResult: template,
   escapeMarkup: function(m) {
      return m;
   }
});

另一个例子是这样定义的

function template(data) {
    if ($(data.html).length === 0) {
        return data.text;
    }
    return $(data.html);
}

$("select").select2({
   ajax: {
        url: 'routeurl',
        dataType: 'json',
        type: 'POST',
        processResults: function(data) {
            return {
                results: data
            };
        },
        cache: true
    },
    allowClear: true,
    placeholder: 'Select at least one element',
    templateResult: template,
    templateSelection: template
});

端点结果格式 json 如此

[{
   id: 0,
   text: 'enhancement',
   html: '<div style="color:green">enhancement</div>'
}, {
   id: 1,
   text: 'bug',
   html: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>'
}, {
   id: 2,
   text: 'success',
   html: 'Success'
}]

将 select2 控件中的文本 属性 更改为 HTML:

$(document).ready(function() {

  function select2OptionFormat(option) {
    var originalOption = option.element;
      if ($(originalOption).data('html')) {
        return $(originalOption).data('html');
      }          
      return option.text;
  }


  $('select').select2({
    formatResult: select2OptionFormat,
    formatSelection: select2OptionFormat,
    escapeMarkup: function(m) { return m; }
  });


});

参考: https://codepen.io/kohnmd/pen/KwYvvM

这是使用 jQuery

的替代选项
$('.select2').on("select2:open", function(e) {
        setTimeout(function(){
            $('#select2-myselect2name-results li').after('my html code here');
        }, 500);
 });

使用

escapeMarkup: function(m) { return m; }

开启XSS漏洞(https://codepen.io/nkorovikov/pen/ZEBdMBP)

我没有找到对数组中的数据使用模板的方法,但是模板非常适用于 ajax 中的数据以及将 select 元素直接添加到 HTML

<select class="templatingSelect2">
        <option value=""></option>
        <option value="usd">USD</option>
        <option value="euro">Euro</option>
        <option value="gbp">Pound</option>
        </select>

(https://codepen.io/SitePoint/pen/bELxVw)