Jquery select2 json数据与optgroup和图像

New*_*Bee 24 javascript jquery jquery-select2

我正在使用带有spring mvc的select2.我从控制器获得了数据,我需要在选项方面显示.但是我希望它们被分组为optgroup,并且我希望将图像附加到其中,可以手动插入,如下所示: -

 <optgroup label="group">
    <option value="imageName">value 1</option>
    <option value="imageName">value 1</option>
    </optgroup>
Run Code Online (Sandbox Code Playgroud)

其中imageName是图像的名称.我想:1)json中的组选项.2)在json中提供此图像属性,以便select2可以形成数据.

这是代码:

$("#my-select").select2({
        data : [ {
            id : 0,
            text : 'enhancement'
        }, {
            id : 1,
            text : 'bug'
        }, {
            id : 2,
            text : 'duplicate'
        }, {
            id : 3,
            text : 'invalid'
        }, {
            id : 4,
            text : 'wontfix'
        } ]
    });
Run Code Online (Sandbox Code Playgroud)

我从我的对象手动创建我的json.所以我可以在这里提供任何数据.有什么建议 ?

Kev*_*own 44

Select2 使用以下逻辑将数据对象映射到<option><optgroup>标记


一个看起来像的数据对象(列表中返回的内容)

{
  'id': 'value-here',
  'text': 'text-here'
}
Run Code Online (Sandbox Code Playgroud)

将映射到<option>看起来像

<option value="value-here">text-here</option>
Run Code Online (Sandbox Code Playgroud)

一个看起来像的数据对象

{
  'text': 'label-here',
  'children': [data_object, data_object]
}
Run Code Online (Sandbox Code Playgroud)

将映射成一个<optgroup>看起来像

<optgroup label="label-here">
  <!-- HTML for the `children` -->
</optgroup>
Run Code Online (Sandbox Code Playgroud)

所以你想要返回的数据对象是

{
  'text': 'group',
  'children': [
    {
      'id': 'imageName',
      'text': 'value 1'
    },
    {
      'id': 'imageName',
      'text': 'value 1'
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)