在Select2中动态添加选项和选项组

23

使用以下HTML代码:

<input type='hidden' id='cantseeme'>

我没有任何问题在动态创建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
});

然而,我似乎无法弄清楚如何以这种方式添加 optgroups。我在github上找到了这个讨论和这篇博客文章,但前者似乎没有讨论动态optgroup的添加,后者我根本就看不懂。

有人有什么想法吗?

2个回答

33

我在您提供的 Github 讨论中找到了答案,optgroups 的对象结构如下:

{
  id      : 1,
  text    : 'optgroup',
  children: [{
                id  : 2,
                text: 'child1'
             },
             {
                id      : 3,
                text    : 'nested optgroup', 
                children: [...]
             }]
}

演示范例


扶额 非常感谢。我为错过那个感到很愚蠢。说实话,在这里没有其他人问过那个问题,我感到很惊讶! - a.real.human.being
1
koala_dev,看起来你发布的那个fiddle不再可用了。 - IcedDante

25

是的,koala_dev上面的答案是正确的。然而,如果您不希望选项组标题成为可选择标签,则从传递给select2的标题中删除"id"字段。子项[ ]仍需要一个"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"
    }, { 
        ...
    }]
}] 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接