具有多个值的 Select2 问题

Select2 issue with multiple values

我有一个网页需要使用 select2 组件。还需要在负载上显示选定的值。在我的 JS 文件中,我有两个构造

JS - 为 choose/remove 选项构建 1

    $("#inp_select_linkproject").select2({
      minimumInputLength: 2,
      maximumSelectionLength: 1,
    ajax: {
          type  : 'POST',
          url: '../../ase.php',
        dataType: 'json',
        delay: 250,
        data: function (term, page) {
          return {
              wildcardsearch: term, // search term
              data_limit: 10,
              data_offset: 0,
              page_mode:"SELECT",
              agent_id:$("#ipn_hdn_userid").val()
          };
        },
        processResults: function (data, page) {
            return { results: data.dataset};
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
});

JS - Construct 2 for catering onload

    $.fn.getCurrentSelect2data = function(){
    $("#inp_select_linkproject").val(null).trigger("change");
    var $element = $('inp_select_linkproject').select2(); // the select element you are working with
     var postFormData =  {
             'eucprid'          : $("#ipn_hdn_eucprid").val()
        };
    var $request = $.ajax({
          type  : 'POST',
          url: '../../ase_x.php',
          data  : postFormData,
        dataType: 'json'
      });

    $request.then(function (data) {
      // This assumes that the data comes back as an array of data objects
      // The idea is that you are using the same callback as the old `initSelection`
        console.log("rowselect,data0-"+data[0].text);
        for (i=0; i<data.length; i++) {
            $('#inp_select_linkproject').append($("<option/>", {
                value: data[i].id,
                text: data[i].text,
                selected: true
            }));
        }
        $('#inp_select_linkproject').trigger('change');
    });
}

现在的问题是重复选择正在发生,并且选择更多选项时重复次数会增加。你能帮我一下吗?

您遇到的问题并非特定于 Select2,如果您从代码中删除对 Select2 的调用,您会发现标准 <select> 也会出现此问题。问题是您在注册新选择之前没有清除旧选择,所以它们只是被附加到最后(并导致重复)。

您可以通过调用

来解决这个问题
$select.empty();

就在您开始向 $select 添加新选项之前。在您的情况下,这意味着将您的回调更改为

// clear out existing selections
$('#inp_select_linkproject').empty();

// add the selected options
for (i=0; i<data.length; i++) {
    $('#inp_select_linkproject').append($("<option/>", {
        value: data[i].id,
        text: data[i].text,
        selected: true
    }));
}

// tell select2 to update the visible selections
$('#inp_select_linkproject').trigger('change');