我正在使用名为Select2的jQuery插件,其中我使用的是Multiselect
。以前我也在为我的另一个网站使用相同的插件,但现在已经很老了。我想,当我从下拉列表中选择选项时,optgroup
会显示如下:Click to see image现在我正在使用的这个插件显示我是这样的:Click to see image我想要选择值的optgroup标签。这是select2
的工作演示:JsFiddle
以前我使用此脚本向optgroup显示值:
function format(item) {
opt = $(item.element);
sel = opt.text();
og = opt.closest('optgroup').attr('label');
return og+' | '+item.text;
}
$("select").select2({
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
$(".select2_sample3").select2({
tags: []
});
使用templateSelection
这是基于您的代码的工作示例
function formatState (item) {
opt = $(item.element);
og = opt.closest('optgroup').attr('label');
return og+' | '+item.text;
};
$('#example').select2({
placeholder: 'Select a Category',
templateSelection: formatState
});
的jsfiddle:https://jsfiddle.net/synz/t2zqjdf0/