0

我有一个网站,它的翻译语言如下。

英语、德语、西班牙语、法语和意大利语。

I have a select box which when selected it should change the location to the translated language.

我遇到的主要问题是弄清楚如何在 url 中没有翻译目录名称的情况下获取 url。

到目前为止我有

var curURL = $('#flagsectionurl').attr('value');
var n=curURL.split("/");        
console.log(n[1]);

input#flasgectionurl 获取当前页面的 url。所以如果我在看

domain.com/de/index

console.log 将显示“de”

选择选择框时,当前执行以下操作

var chosenCountry = data.selectedData.value;
window.location = "/"+chosenCountry+$('#flagsectionurl').attr('value');

在保留当前页面的同时更改目录的最佳方法是什么?由于此方法不起作用,因为它最终会转到 domain.com/de/de/index

4

1 回答 1

0

您正在向 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.

于 2012-11-06T09:53:10.983 回答