【问题标题】:Is there a way to make a button redirect to the page of the current link, but in another language有没有办法让按钮重定向到当前链接的页面,但是用另一种语言
【发布时间】:2021-10-12 14:05:45
【问题描述】:

您好,我有 2 个使用两种不同语言的博客。所有链接都是相同的,只是英文博客的博客名称后有一个“-en”后缀,而希腊博客有一个“-el”后缀。

我想在某处放置一个使用当前页面链接的按钮。例如“https://cookwithnick-en.blogspot.com/2021/07/mini-piroshki.html”,将其转换为“https://cookwithnick-el.blogspot.com/2021/07/mini-piroshki. html”并在同一个选项卡上打开它。

我已经设法制作了以下代码,但不起作用:

<input type="button" onclick="location.href=window.location.href.replace("en", "el");" value="Greek" />

如果 ".replace("en", "el");"丢失(它重定向到完全相同的页面)我想将链接转换为其他语言。

感谢您的宝贵时间和建议。

【问题讨论】:

  • 您还有问题吗?
  • @Danial 不,我听从了你的建议,谢谢!

标签: javascript html replace hyperlink html-input


【解决方案1】:

您需要对字符串使用单引号,因为onclick 属性的值用双引号括起来。

<input type="button" onclick="location.href=window.location.href.replace('en', 'el');" value="Greek" />

但是,通常最好使用addEventListener 而不是内联事件处理程序。

【讨论】:

  • 非常感谢您的建议。
  • @NIKOLAOSRAPANIS 很高兴为您提供帮助。
  • @NIKOLAOSRAPANIS 如果这解决了您的问题,请考虑accepting
【解决方案2】:

只需将.replace("en", "el")中的双引号替换为单引号即可,所以:

<input type="button" onclick="location.href=window.location.href.replace('en', 'el');" value="Greek" />

但是,最好这样做:

<input type="button" id="change-lang" value="Greek" />

<script>
    document.getElementById("change-lang").addEventListener("click", function(){
        location.href=window.location.href.replace('en', 'el');
    });
</script>

【讨论】:

  • 你好。谢谢您的帮助。在 HTML 中不“流利”,我无法理解第二种方式的工作方式有何不同。当你说更好时,你的意思是代码会有更好的结果,或者它不会有很多错误,或者只是更好的拼写?
  • 没有什么不同。这只是最佳实践@RAPANIS
猜你喜欢
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 2018-07-27
  • 2017-05-22
相关资源
最近更新 更多