javascript - 如何在 jQuery select2 中显示 optgroup 标签+值

标签 javascript jquery jquery-select2

我正在使用名为 Select2 的 jQuery 插件,其中我使用了Multiselect。以前我也在我的另一个网站上使用了相同的插件但那个插件现在已经很旧了。我想,当我从下拉列表中选择选项时,会显示 optgroup ,如下所示:Click to see image 现在我正在使用的这个插件向我显示如下:Click to see image 我想要具有选择值(value)的 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/

资源:https://select2.org/selections#templating

关于javascript - 如何在 jQuery select2 中显示 optgroup 标签+值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916324/

相关文章:

javascript - 带重定向的 AngularJS 路由

Javascript 热图 ReferenceError h337.create

jquery - 使用 tablesorter 根据另一列的值对一列进行排序?

javascript - 在 IWebBrowser2 中加载 jQuery 时出现脚本错误

javascript - 在数据响应中选择#id.html

javascript - jquery通过css自定义select2组件

electron - 为什么 Select2 不会覆盖 Electron 中的正常选择框?

php - Symfony Form Select2 允许用户输入新值

javascript - 第一次替换后如何停止替换字母?

javascript - 拖放并使该元素响应