How can I show more than one white space character in a row in a select2 data row?

假如想象 提交于 2019-12-12 02:42:13

问题


I'm using Select2 and I use the {data: [{id:1, text: "..."}] approach to define the options. I want to format each option by grouping the substring it's made up of using more than one white space character. So something like this:

{data: [
    {id:1, text: "Trees     -     Oak"},
    {id:2, text: "Trees     -     Pine"},
    {id:3, text: "Seas      -     North Sea"},
    {id:4, text: "Seas      -     Baltic Sea"}
]}

When I do this they show up as one space in the resulting dropdown (the default HTML way of dealing with spaces). When I use   instead of space they show up as the string " " in the dropdown instead of as spaces.

{data: [
    {id:1, text: "Trees   -   Oak"},
    {id:2, text: "Trees   -   Pine"},
    {id:3, text: "Seas   -   North Sea"},
    {id:4, text: "Seas   -   Baltic Sea"}
]}

Is there a way to preserve all the spaces I define in the text attribute of the data item?


回答1:


Don't you want to use optgroups instead?

{data: [
  {
    text: "Trees",
    children: [
      {id:1, text: "Oak"},
      {id:2, text: "Pine"},
    ]
  },
  {
    text: "Seas",
    children: [
      {id:1, text: "North Sea"},
      {id:2, text: "Baltic Sea"},
    ]
  },
]}

or try to add

white-space: pre;

in css-class of select's item to preserve all the whitespaces in the string.

As koenpeters said in comments,for default theme css will look like:

.select2-container--default .select2-results__option {
  white-space: pre;
}



回答2:


An alternative to the answer that Yuri Gor gave is to use   and include escapeMarkup to the select2 creation.

$("#isOfTheSelectNode").select2({
    escapeMarkup: function (m) { return m; }
});

The drawbacks are:

  • None of the html markup will be escaped, which may result in strange option elements if the text contains HTML.
  • Items that contain   will not be matched when you search for a space.

I think Yuri Gor's answer is better if you only want to allow multiple spaces to be rendered as such.



来源:https://stackoverflow.com/questions/39679566/how-can-i-show-more-than-one-white-space-character-in-a-row-in-a-select2-data-ro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!