【问题标题】:Reinit select2 data重新初始化 select2 数据
【发布时间】:2021-03-01 19:53:55
【问题描述】:

当国家选择的选择值为加拿大时,我想重新初始化区域选择的数据值。否则地区列表应该保持默认,所以我们地区。

到目前为止,我有以下代码,但它始终保留在美国地区。我也尝试再次销毁并重新初始化,但不幸的是没有任何成功。

var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json',
    regionsList = 'https://rawcdn.githack.com/levipadre/US-and-Canada-states-json/de677490123474288ae2777d04f1728e1f1833a9/us-states.json',
    countrySelect = $('.country'),
    regionSelect = $('.region');

$.ajax({
    type: 'GET',
    url: countriesList,
    dataType: 'json',
    success: function(response) {
        countrySelect.select2({
            data: response.map(item => ({
                id: item.alpha2,
                text: item.name
            })),
            width: '100%',
            dropdownAutoWidth: true,
            matcher: startWithMatcher,
            placeholder: 'Select country'
        });
    }
});

countrySelect.on('select2:select', function (e) {
    var data = e.params.data;
    
    console.log(data.id);
    if(data.id == "ca") {
        regionsList = 'https://rawcdn.githack.com/levipadre/US-and-Canada-states-json/de677490123474288ae2777d04f1728e1f1833a9/canada-states.json';
        getRegion(regionsList);
    } else {
        getRegion(regionsList);
    }
});

function getRegion(region){
    $.ajax({
        type: 'GET',
        url: region,
        dataType: 'json',
        success: function(response) {
            regionSelect.select2({
                data: response.map(item => ({
                    id: item.id,
                    text: item.text
                })),
                width: '100%',
                dropdownAutoWidth: true,
                matcher: startWithMatcher,
                placeholder: 'Select region'
            });
        }
    });
}

getRegion(regionsList);

function startWithMatcher(params, data) {
    params.term = params.term || '';
    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
    }
    return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<select class="country">
  <option></option>
</select>

<br>
<br>
<br>

<select class="region">
  <option></option>
</select>

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    您当前的逻辑是将新区域附加到 select2 实例。要删除原始条目,您可以在添加新的 option 元素之前在 select 上调用 empty()。或者,如果你想保留第一个空的option,那么你可以使用这个:

    regionSelect.children().not(':first').remove();
    

    这是一个工作示例:

    var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json',
      regionsList = 'https://rawcdn.githack.com/levipadre/US-and-Canada-states-json/de677490123474288ae2777d04f1728e1f1833a9/',
      countrySelect = $('.country'),
      regionSelect = $('.region');
    
    $.ajax({
      type: 'GET',
      url: countriesList,
      dataType: 'json',
      success: function(response) {
        countrySelect.select2({
          data: response.map(item => ({
            id: item.alpha2,
            text: item.name,
            source: item.alpha2 == 'ca' ? 'canada-states.json' : 'us-states.json'        
          })),
          width: '100%',
          dropdownAutoWidth: true,
          matcher: startWithMatcher,
          placeholder: 'Select country'
        });
      }
    });
    
    countrySelect.on('select2:select', function(e) {
      var data = e.params.data;
      regionSelect.show();
      getRegion(regionsList + e.params.data.source);
    });
    
    function getRegion(region) {
      $.ajax({
        type: 'GET',
        url: region,
        dataType: 'json',
        success: function(response) {
          regionSelect.children().not(':first').remove(); // remove old options
          regionSelect.select2({
              data: response.map(item => ({
                id: item.id,
                text: item.text
              })),
              width: '100%',
              dropdownAutoWidth: true,
              matcher: startWithMatcher,
              placeholder: 'Select region'
            });
        }
      });
    }
    
    function startWithMatcher(params, data) {
      params.term = params.term || '';
      if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
        return data;
      }
      return false;
    }
    .region { display: none; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    
    <select class="country">
      <option></option>
    </select>
    <br /><br />
    <select class="region">
      <option></option>
    </select>

    另外请注意,我修正了您的逻辑以允许在美国/加拿大各州之间进行更改,因为一旦更改,原始逻辑将始终保留加拿大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2019-12-05
      • 2011-03-13
      • 2016-04-18
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多