【发布时间】:2017-05-06 20:07:20
【问题描述】:
我想为新链接添加当前路径(以便能够在同一页面上切换语言)。
如何将当前的window.location.pathname 添加到新的 URL?
【问题讨论】:
-
查看 history.pushState
标签: javascript url redirect path window
我想为新链接添加当前路径(以便能够在同一页面上切换语言)。
如何将当前的window.location.pathname 添加到新的 URL?
【问题讨论】:
标签: javascript url redirect path window
你可以看看js历史对象:
function changeLanguage(code){
//possible languages
var codes=["en","de"];
if(!codes.find(function(a){return a==code})){
//language not available
console.error("unknown language");
return;
}
//get current url
url=window.location.pathname;
for(i=0;i<codes.length;i++){
//replace current language with new language
url=url.replace(codes[i],code);
}
//"redirect" url without reloading the page
history.pushState({},"new title",url);
//replace content...
}
//example:
changeLanguage("de");
这要求 url 包含语言代码:
http://example.com/en/main/
->
http://example.com/de/main/
【讨论】: