更改 Select2 以显示 'n of m items selected'

Change Select2 to display 'n of m items selected'

我喜欢在启用标记的情况下使用 Select2 插件,如本例所示: https://select2.github.io/examples.html#tags

不过我想将其更改为显示类似

的文本

n of m items selected

当有超过 3 个项目时 selected。单击该框后,您将看到确切的项目,就像现在一样。

然后 select 框可以渲染得更小并且消耗更少 space。

这似乎不是配置选项。您知道在代码的哪个位置更改此行为吗?

https://select2.github.io/examples.html#events

有了事件你就可以做到。触发 select 事件并更新您的文本。

你可以这样轻松搞定。不需要 rape select2 :)

$("#singleSelectExample").select2({
  closeOnSelect: false
});

$('#singleSelectExample').on('change', function() {
  var selected = $(this).val().length; 
  var of = $(this).find('option').length;
  $(this).parent().find('.select2-selection ul').html('Selected ' + selected + ' of ' + of + '  items.')
});

JSFIDDLE