javascript 如何使用 window.location.href.replace 在 href url 中切换语言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21867856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:53:20  来源:igfitidea点击:

How to use window.location.href.replace to switch language in the href url?

javascriptjqueryhtml

提问by user3108698

I have a link that is used to switch languages in my site. When the user click on the link I want it to direct user to the chinese version of the page that is located inside the /ch/ folder.

我有一个链接,用于在我的网站中切换语言。当用户单击该链接时,我希望它将用户定向到位于 /ch/ 文件夹内的页面的中文版本。

For example, when user is on mysite.com/account/en/index.html, when click on the link, user should be redirected to mysite.com/account/ch/index.html

例如,当用户在 mysite.com/account/en/index.html 上时,当点击链接时,用户应该被重定向到 mysite.com/account/ch/index.html

I tried the below code but it is not working. Anyone know a better code?

我尝试了下面的代码,但它不起作用。有人知道更好的代码吗?

<li class="lang"><a id="langswitch" href="javascript: window.location.href.replace('/en/', '/ch/');" ><img src="/images/account/buttons/chinese.jpg" alt="chinese language" align="top" /></a></li>

回答by Will P.

I believe all that you are missing is

我相信你所缺少的只是

window.location = window.location.href.replace('/en/', '/ch/');

window.location = window.location.href.replace('/en/', '/ch/');

回答by Venkat Reddy

why cant you use

为什么你不能使用

<li class="lang"><a id="langswitch" href="mysite.com/account/cn/index.html" ><img src="/images/account/buttons/chinese.jpg" alt="chinese language" align="top" /></a></li>