【问题标题】:Jquery select2 json data with optgroup and images带有 optgroup 和图像的 Jquery select2 json 数据
【发布时间】:2015-10-05 18:53:50
【问题描述】:

我将 select2 与 spring mvc 一起使用。我从控制器中获取了需要在此处显示的数据选项。但我希望将它们分组为 optgroup,并且我希望将图像附加在其中,可以手动插入,如下所示: -

 <optgroup label="group">
    <option value="imageName">value 1</option>
    <option value="imageName">value 1</option>
    </optgroup>

其中 imageName 是图像的名称。我想要 : 1) json 中的组选项。 2)在json中提供这个image属性,这样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'
        } ]
    });

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

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    Select2 使用以下逻辑将数据对象映射到 &lt;option&gt;&lt;optgroup&gt; 标签


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

    {
      'id': 'value-here',
      'text': 'text-here'
    }
    

    将映射到一个看起来像的&lt;option&gt;

    <option value="value-here">text-here</option>
    

    一个看起来像的数据对象

    {
      'text': 'label-here',
      'children': [data_object, data_object]
    }
    

    将被映射成一个看起来像的&lt;optgroup&gt;

    <optgroup label="label-here">
      <!-- HTML for the `children` -->
    </optgroup>
    

    所以您要返回的数据对象是

    {
      'text': 'group',
      'children': [
        {
          'id': 'imageName',
          'text': 'value 1'
        },
        {
          'id': 'imageName',
          'text': 'value 1'
        }
      ]
    }
    

    【讨论】:

    • 是否还有映射到 CSS 类的属性?
    猜你喜欢
    • 2019-12-18
    • 2018-08-18
    • 2022-07-07
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2013-05-12
    相关资源
    最近更新 更多