【问题标题】:Language redirection with javascript使用 javascript 进行语言重定向
【发布时间】:2014-03-17 04:04:41
【问题描述】:

我必须在 Business Catalyst 中建立一个多语言网站(不是我的选择),语言切换器的唯一选择,并且链接 rel="alternate" 是 JS。 经过大量的试验和错误,我得到了这个工作:

<script type="text/javascript">
document.write("<ul>"); 
document.write("<li><a href=\"http://localhost:8888/en/" + location.pathname + "\">English</a></li>");
document.write("<li><a href=\"http://localhost:8888/fr/" + location.pathname + "\">French</a></li>");
document.write("<ul>"); 
</script>

唯一的问题是它很慢而且可能写得不好。 有没有更好的方法来编写代码?也许加载速度更快并且可能使用 jQuery?

非常感谢您的帮助

安东尼奥

【问题讨论】:

  • 嗨安东尼奥。 document.write 实际上在哪里添加列表?在文件的末尾?第二,什么是慢?写清单?因为您没有任何其他操作。此外,在您的本地主机或实时服务器上是否很慢。
  • 您好 Joraid,非常感谢您的回复。语言切换器将位于网站的页眉和页脚中。当我说慢时,我的意思是从页面出现到显示实际链接需要 1 秒。

标签: javascript jquery multilingual


【解决方案1】:

您可以在 html 中包含以下内容。

<ul id="multilang">
    <li>
        <a href="http://localhost:8888/en/">English</a>
    </li>
    <li>
        <a href="http://localhost:8888/fr/">French</a>
    </li>
</ul>

然后使用jQuery来操作url。

$(function () {
    $.each($("#multilang a"), function () {
        $(this).attr('href', $(this).attr('href') + location.pathname);
    });
});

【讨论】:

  • 非常感谢Sajith,太好了,我在JS方面还不到菜鸟……但我正在努力学习
【解决方案2】:

我通常建议避免使用基于字符串的动态 html,因为随着时间的推移,它往往难以维护。相反,我建议使用某种基于模板的解决方案。有几个选项,但一个流行的框架是 KnockoutJs

http://knockoutjs.com/

【讨论】:

  • 谢谢TGH,我去看看!
【解决方案3】:

1- 一个首发。 document.write 将用您的列表替换整个 DOM,因此,我建议将列表附加到 html 元素。

2- 为了提高性能,尽量减少函数调用以减少开销。选项 1:准备 html 并将其写入一个字符串,然后附加该字符串。例如。

var lang = "<ul><li>stuff...</li><li>other stuff....</li></ul>";

或者,为了可读性,

lang = "<ul>";
lang = "<li><a href=\"http://localhost:8888/en/" + location.pathname + "\">English</a></li>";
lang = "<li><a href=\"http://localhost:8888/fr/" + location.pathname + "\">French</a></li>";
lang = "</ul>";

然后

$("#change_lang").html(lang);//change_lang is a div <div id="change_lang"> that you have prepared to put the links inside. 

3- 也许您可以直接从服务器加载 html,无需 JS 为您在屏幕上打印放在.html页面中(我不确定你的页面结构,所以我不知道为什么这种方法可能不适合你)但是直接加载html而不等待JS 和 JQuery 加载将使显示速度更快。

<ul>
    <li><a href="http://localhost:8888/en/yoursite.html">English</a></li>
    <li><a href="http://localhost:8888/fr/yoursite.html">French</a></li>
</ul>

4- 还可以尝试将您的 JS 代码放在单独的文件中,然后 minify 它们以减小大小并因此减少加载时间。将 JS 放在单独的文件中允许浏览器 cache 它们并消除每次加载它们的需要。搜索PageSpeed,向您展示提高网站性能的各种方法。

【讨论】:

  • 您好 Joraid,非常感谢您的回复,我实际上将它们分开并缩小了,但在这种特殊情况下,我真的不知道该写什么......经过大量的谷歌搜索和错误我用那个凌乱的代码出来......
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多