如何使用JSON在select2中设置optgroup [英] How to set optgroup in select2 using JSON

查看:70
本文介绍了如何使用JSON在select2中设置optgroup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将某些项目分组在单独的 optgroups 中?应该在不同的 JSON 对象中设置? select2 文档中没有任何示例.任何帮助或指导都会有所帮助.

How some items can be group in separate optgroups? Should be set in different JSON objects? There is no example in select2 documentation. Any help or direction would be helpful.

以下是 select 群体的示例代码:

Here is example code of select population:

jQuery 代码:

 var data = [
          { id: 0, text: 'enhancement' }, 
          { id: 1, text: 'bug' }, 
          { id: 2, text: 'duplicate' }, 
          { id: 3, text: 'invalid' }, 
          { id: 4, text: 'wontfix' }
    ];

    $(".js-example-data-array").select2({
      data: data
    });

推荐答案

您需要在数组中设置 children 属性,以允许 optgroups .

You need to set children attribute in your array to allow optgroups.

示例: https://jsfiddle.net/DinoMyte/8odneso7/13/

var data = [{
    id: 0,
    text: 'enhancement',
    children: [{
        id: 5,
        text: 'enhancement child1'
      },
      {
        id: 6,
        text: 'enhancement child2'

      }
    ]
  },
  {
    id: 1,
    text: 'bug'
  },
  {
    id: 2,
    text: 'duplicate'
  },
  {
    id: 3,
    text: 'invalid'
  },
  {
    id: 4,
    text: 'wontfix'
  }
];

$(".js-example-data-array").select2({
  data: data,
  width: 'auto'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select class="js-example-data-array">
</select>

这篇关于如何使用JSON在select2中设置optgroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆