【问题标题】:How to set optgroup in select2 using JSON如何使用 JSON 在 select2 中设置 optgroup
【发布时间】:2016-03-29 04:00:54
【问题描述】:

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

这是select人口的示例代码:

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
    });

【问题讨论】:

  • 本站没有这个工作的例子,开发者使用'$(".js-source-states").html();'填满它们。并在填充后移除对象
  • 那么,没有办法只使用 JSON 对象填充 select 吗?

标签: jquery json jquery-select2


【解决方案1】:

您需要在数组中设置children 属性以允许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>

【讨论】:

  • 太棒了!我已经在我的项目中进行了测试,并按预期工作!谢谢
猜你喜欢
  • 2018-08-18
  • 2019-12-18
  • 2022-07-07
  • 2015-01-13
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
相关资源
最近更新 更多