1

我正在为客户创建一个双语网站。将创建两个不同语言版本的站点并将其存储在两个文件夹中:/en/ /chi/

我想要做的是创建一个链接以在两种语言之间切换。在概念层面上,我理解 Javascript 可以检测当前 URL 并将其拆分为不同的组件,修改其中的部分(在这种情况下在 /en/ 和 /chi/ 之间更改),然后在链接被点击。

但我对 javascript 的了解为零,所以我不知道如何执行......我遇到了这个页面: http ://css-tricks.com/snippets/javascript/get-url-and-url-parts-in -javascript/ 但它没有说明如何修改并转到新链接。

您的帮助将不胜感激!!

4

3 回答 3

2

为了不破坏可用性考虑,例如Shift + Click to open in a new window,您应该创建一个<a>指向其他语言 URL 的普通旧链接 ( )。通过 JavaScript 构建链接没有任何问题,但您也可以在服务器上使用 PHP 或您使用的任何模板语言来完成。

如果您决定要这样做,这是一个使用 JavaScript 执行此操作的脚本。

<!DOCTYPE html>
<body>
  Content before the link.
  <script>
    (function () {
      // this assumes you're on the en version and want to switch to chi
      var holder = document.createElement("div");
      var url = window.location.href.replace("/en/", "/chi/");
      var link = document.createElement("a");

      link.innerText = "Chewa"; // or whatever the link should be
      link.href = url;
      holder.appendChild(link);
      document.write(holder.innerHTML);
    })();
  </script>
  Content after the link.
</body>
于 2012-03-29T17:56:59.993 回答
0

如果您只是想获取完整的 URL 并替换/en//chi/或反之亦然,请使用下面的代码。

HTML

<span onclick="SwitchLang()">View [Some other Language]</span>

JavaScript

function SwitchLang() {
    //Does URL contain "/en/"?
    if(window.location.href.indexOf("/en/") != -1) {
        //URL contain "/en/", replace with "/chi/"
        window.location.href = window.location.href.replace("/en/", "/chi/");
    }
     //Does URL contain "/chi/"?
    else if(window.location.href.indexOf("/chi/") != -1) {
        //URL contain "/chi/", replace with "/en/"
        window.location.href = window.location.href.replace("/chi/", "/en/");
    }
}

或者,更简洁一点(未注释版本)

function SwitchLang() {
    if(window.location.href.indexOf("/en/") != -1)
        window.location.href = window.location.href.replace("/en/", "/chi/");
    else if(window.location.href.indexOf("/chi/") != -1)
        window.location.href = window.location.href.replace("/chi/", "/en/");
}

注意:在 JS 中,当你修改 时window.location.href,会自动加载新的 URL。

这是一个供您使用的工作小提琴。

于 2012-03-29T12:15:32.443 回答
-1

看来您需要更改window.location.pathname. 例如:

// assuming the url `http://www.example.org/en/foo/bar/page.html`

var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");

看:

https://developer.mozilla.org/en/DOM/window.location

于 2012-03-29T12:19:25.690 回答