【问题标题】:Add the current path for the new link为新链接添加当前路径
【发布时间】:2017-05-06 20:07:20
【问题描述】:

我想为新链接添加当前路径(以便能够在同一页面上切换语言)。

如何将当前的window.location.pathname 添加到新的 URL?

【问题讨论】:

  • 查看 history.pushState

标签: javascript url redirect path window


【解决方案1】:

你可以看看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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 2012-03-09
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 2011-05-06
    • 2017-06-09
    相关资源
    最近更新 更多