javascript Jquery select2 json 数据与 optgroup 和图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31452318/
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
Jquery select2 json data with optgroup and images
提问by New Bee
I am using select2 with spring mvc. I got the data from my controller that I need to display here in terms of options. But I want them to be grouped as optgroup and also I want images to be appended in it which can be inserted manually as given below : -
我在 spring mvc 中使用 select2。我从我的控制器中获得了我需要在选项方面显示的数据。但我希望它们被分组为 optgroup,并且我希望将图像附加到其中,可以手动插入,如下所示: -
<optgroup label="group">
<option value="imageName">value 1</option>
<option value="imageName">value 1</option>
</optgroup>
Where imageName is the name of image. I want to : 1) Group options in json. 2) Provide this image attribute in json so that select2 can form the data.
其中 imageName 是图像的名称。我想:1)json 中的组选项。2)在json中提供这个image属性,以便select2可以形成数据。
Here is the code :
这是代码:
$("#my-select").select2({
data : [ {
id : 0,
text : 'enhancement'
}, {
id : 1,
text : 'bug'
}, {
id : 2,
text : 'duplicate'
}, {
id : 3,
text : 'invalid'
}, {
id : 4,
text : 'wontfix'
} ]
});
I am creating my json manually from my objects. So I can provide any data here. Any suggestions ?
我正在从我的对象手动创建我的 json。所以我可以在这里提供任何数据。有什么建议 ?
回答by Kevin Brown
Select2 maps data objects to <option>
and <optgroup>
tags using the following logic
SELECT2映射数据对象<option>
和<optgroup>
使用下列逻辑标记
A data object (what is returned in the list) that looks like
看起来像的数据对象(列表中返回的内容)
{
'id': 'value-here',
'text': 'text-here'
}
Will be mapped to an <option>
that looks like
将被映射到一个<option>
看起来像
<option value="value-here">text-here</option>
A data object that looks like
一个看起来像的数据对象
{
'text': 'label-here',
'children': [data_object, data_object]
}
Will be mapped into an <optgroup>
that looks like
将被映射成一个<optgroup>
看起来像
<optgroup label="label-here">
<!-- HTML for the `children` -->
</optgroup>
So the data object that you are looking to return is
所以你要返回的数据对象是
{
'text': 'group',
'children': [
{
'id': 'imageName',
'text': 'value 1'
},
{
'id': 'imageName',
'text': 'value 1'
}
]
}