在Select2中动态添加选项和optgroup

a.r*_*ing 23 javascript jquery jquery-select2

使用以下html:

<input type='hidden' id='cantseeme'>
Run Code Online (Sandbox Code Playgroud)

我在动态创建Select2控件并添加我的选项时没有遇到任何问题:

// simplified example
var select2_ary = [];

select2_ary.push({
    id : "one",
    text : "one"
});
select2_ary.push({
    id : "two",
    text : "two"
});

$("#cantseeme").select2({
    placeholder : "Pick a number",
    data : select2_ary
});
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法弄清楚如何添加optgroups这种方式.我在github上发现了这个讨论,并在博客上发表了这篇文章,但前者似乎没有讨论动态optgroup添加,我根本无法理解后者.

有人有主意吗?

koa*_*dev 33

我发现答案埋没在你链接的github讨论中,对象结构optgroups如下:

{
  id      : 1,
  text    : 'optgroup',
  children: [{
                id  : 2,
                text: 'child1'
             },
             {
                id      : 3,
                text    : 'nested optgroup', 
                children: [...]
             }]
}
Run Code Online (Sandbox Code Playgroud)

演示小提琴


小智 25

是的,koala_dev的答案是正确的.但是,如果您不希望选项组标题成为可选标记,则从传递给select2的标题中删除"id"字段.Children []项目仍需要"id"字段才能选择.例如:

// `Header One` Is Selectable
[{
    id       : 0,
    text     : "Header One",
    children : [{
        id   : 0,
        text : "Item One"
    }, { 
        ...
    }]
}] 


// `Header One` Is Not Selectable
[{
    text     : "Header One",
    children : [{
        id   : 0,
        text : "Item One"
    }, { 
        ...
    }]
}] 
Run Code Online (Sandbox Code Playgroud)