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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18346518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:34:34  来源:igfitidea点击:

Dynamically adding options and optgroups in Select2

javascriptjqueryjquery-select2

提问by a.real.human.being

With the following html:

使用以下 html:

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

I'm having no trouble creating a Select2 control dynamically, and adding my options:

我在动态创建 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
});

However, I can't seem to figure out how to add optgroupsthis way. I found thisdiscussion on github, and thisarticle on a blog, but the former doesn't seem to discuss dynamic optgroupadditions and I simply can't make any sense of the latter.

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

Anyone have any ideas?

有人有想法么?

回答by koala_dev

I found the answer buried inside the github discussion you linked to, the object structure for optgroupsis as follows:

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

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

Demo fiddle

演示小提琴

回答by bradfordh

Yes, koala_dev's answer above is correct. However, if you do not want option group headers to be selectable tags, then remove the "id" field from headers that you pass into select2. Children[ ] items still need an "id" field to be selectable. For example:

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