【问题标题】:Dynamically adding options and optgroups in Select2在 Select2 中动态添加选项和 optgroup
【发布时间】:2013-08-23 04:20:50
【问题描述】:

使用以下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 上找到了 this 讨论,在博客上找到了 this 文章,但前者似乎没有讨论动态的 optgroup 添加,我根本无法理解后者。

有人有什么想法吗?

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    我在你链接到的 github 讨论中找到了答案,optgroups 的对象结构如下:

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

    Demo fiddle

    【讨论】:

    • facepalm 非常感谢。我因为错过了这个而感到很愚蠢。 Tbh,很惊讶以前没有人在这里问过这个问题!
    • koala_dev,你发的小提琴好像失效了
    【解决方案2】:

    是的,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"
        }, { 
            ...
        }]
    }] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 2015-05-31
      • 2015-08-29
      • 2021-09-03
      相关资源
      最近更新 更多