【发布时间】:2020-12-25 00:40:04
【问题描述】:
当我从下拉列表中选择国家时,我需要更改 URL 中的国家代码。
目前我的下拉列表中只有 3 个国家/地区,但是当我从 SG (testing.com/sg/features) 切换到 IE 时,生成的 URL 变为 (testing.com/ie/sg/features)。当我从 IE(testing.com/ie/features) 切换到 SG(testing.com/sg/features) 时,它工作正常。
<form name="form1">
<select class="region regionTopBar" onchange="formChanged(this);" name="country" size="1" style="font-family: inherit; padding: 5px; border:0px; outline:0px;">
<option value="/">International</option>
<option value="sg/">Singapore</option>
<option value="ie/">Ireland</option>
</select>
</form>
<script>
function formChanged(form) {
var formCountryCode = form.options[form.selectedIndex].value;
var formCountryName = form.options[form.selectedIndex].text;
if (formCountryCode !== null) {
if (localStorage) {
localStorage.country = formCountryCode ;
localStorage.currentSite = formCountryName ;
}
if(formCountryCode == "sg/"){
var url = window.location.href.replace("testing.com/", "testing.com/sg/");
location = url;
}
else if(formCountryCode == "ie/"){
var url = window.location.href.replace("testing.com/", "testing.com/ie/");
location = url;
}
//remove country code from URL when International is selected
else {
var thisLocation = window.location.href;
var splitLoc = thisLocation.split('/');
var newLocation = "";
for (let i = 0; i < splitLoc.length; i++){
if (splitLoc[i] !== "sg" && splitLoc[i] !== "ie")
newLocation += splitLoc[i] + '/';
}
newLocation = newLocation.substring(0, newLocation.length - 1);
location = newLocation ;
}
}
}
</script>
添加这样的 if else 可以解决问题,但随着国家/地区数量的增加,这将是一团糟。
else if(formCountryCode == "ie/" && window.location.href.indexOf("sg/") < 1){
var url = window.location.href.replace("testing.com/", "testing.com/ie/");
location = url;
}
else if(formCountryCode == "ie/" && window.location.href.indexOf("sg/") > 0){
var url = window.location.href.replace("testing.com/sg/", "testing.com/ie/");
location = url;
}
所以我正在寻找一种动态的方式来实现这一点。
【问题讨论】:
-
是 testing.com 你的主机名,即testing.com ?
-
不,但这只是域的一个例子。
标签: javascript substring href subdirectory country-codes