如何在select2选项中呈现html

时间:2016-04-01 15:59:33

标签: jquery html jquery-select2 jquery-select2-4

在从远程源加载的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>

如何将html内容添加到select2选项?

7 个答案:

答案 0 :(得分:26)

如果我没弄错的话,你只能在设置templateResult和templateSelection选项时让它们呈现HTML并让它们返回一个jQuery对象。

&#13;
&#13;
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); },
      
    })
&#13;
    <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>
 
&#13;
&#13;
&#13;

答案 1 :(得分:21)

好的,玩了一段时间后找到了一个有效的解决方案,所以我会在这里回答我自己的问题。

这里的关键是构建一个包含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>

答案 2 :(得分:7)

只需将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;
   }
});

答案 3 :(得分:4)

另一个例子是这样定义的

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'
}]

答案 4 :(得分:0)

使用

escapeMarkup: function(m) { return m; }

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

我没有找到将模板用于数组数据的方法,但是模板非常适用于来自 ajax 的数据以及将选择元素直接添加到 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)

答案 5 :(得分:-1)

在select2控件中将text属性更改为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

答案 6 :(得分:-1)

这是使用 jQuery 的替代选项

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