【发布时间】: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