select2 - 动态更改配置

select2 - Change configuration dynamically

如果用户选择了第一个选项,我将尝试动态覆盖 select2 中的 maximumSelectionLength 配置选项,我尝试按如下方式进行...

$(".some-div select").on("select2:open", function(e) {

    if(e.target.options[0].selected) {
        $(this).select2({
           maximumSelectionLength: 1
        });
    }

});

但它总是给我这个错误Uncaught TypeError: Cannot read property 'query' of null

我该怎么做?

有一种获取项目索引的本机方法evt.params.data.element.index,所以 只需这样做:

$('#example').select2({
  maximumSelectionLength: 5
});

$("#example").on("select2:select", function(evt) {
  let index = evt.params.data.element.index; // get index 
  if (index === 0) {
    $('#example').select2({ //re-init
      maximumSelectionLength: 1
    });
  }
});

JSFiddle

您可以在 else

恢复 maximumSelectionLength 的默认值