[英]Dynamically adding options and optgroups in Select2
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 optgroups
this way. 但是,我似乎无法弄清楚如何以这种方式添加
optgroups
。 I found this discussion on github, and this article on a blog, but the former doesn't seem to discuss dynamic optgroup
additions and I simply can't make any sense of the latter. 我在github上发现了这个讨论,并在博客上发表了这篇文章,但前者似乎没有讨论动态的
optgroup
添加,而我根本无法理解后者。
Anyone have any ideas? 有人有主意吗?
I found the answer buried inside the github discussion you linked to, the object structure for optgroups
is as follows: 我发现答案隐藏在你链接的github讨论中,
optgroups
的对象结构如下:
{
id : 1,
text : 'optgroup',
children: [{
id : 2,
text: 'child1'
},
{
id : 3,
text : 'nested optgroup',
children: [...]
}]
}
Yes, koala_dev's answer above is correct. 是的,koala_dev的答案是正确的。 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.
但是,如果您不希望选项组标题成为可选标记,则从传递给select2的标题中删除“id”字段。 Children[ ] items still need an "id" field to be selectable.
Children []项目仍需要“id”字段才能选择。 For example:
例如:
// `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"
}, {
...
}]
}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.