您正在向 URL 添加一个新国家/地区,但并未删除当前国家/地区。
您从chosenCountry
变量开始,然后附加$('#flagsectionurl').attr('value')
已包含国家/地区的当前 URL。
您想替换 URL 的国家/地区部分,同时保留其余部分。为此,您可以执行以下操作(基于记录到控制台的代码中显示的 URL 结构):
var new_url = $('#flagsectionurl').attr('value');
new_url = url.split("/");
new_url[1] = data.selectedData.value;
window.location = new_url.join("/");
编辑:
Because of the issue you have raised where for English it does not use the above URL convention, you need to keep track of the current language (including if it is English), if you have not already. Then if the current selection is English and you are changing to another language, you will need to add a new item to the array after splitting it. If you are going from another language to English, you will need to remove the item in the array at position 1.
var new_lang = data.selectedData.value;
var new_url = $('#flagsectionurl').attr('value');
new_url = url.split("/");
if (cur_lang == 'en') {
new_url.splice(1,0,new_lang);
}
else if (new_lang == 'en') {
new_url.splice(1,1);
}
else {
new_url[1] = new_lang;
}
window.location = new_url.join("/");
The above code works off the assumption the current language and new language cannot be the same, you will need to check for this if you are not already.