【发布时间】:2013-05-22 15:04:36
【问题描述】:
使用下面描述的脚本,我想知道是否有办法在页面上放置一个链接,以允许用户在页面加载后更改显示的语言。最初,它会显示用户的默认语言,但我希望允许他们动态更改它。
谢谢!
托马斯
通常的方法是将语言分开(一个 HTML 文件 例如,每种语言)并以该语言发回内容 他们要。您可以尝试解析 Accept-Language 标头并发送 返回最接近的匹配;你可能想要包含一种语言 还有某种选择小部件。
如果您真的想使用 JavaScript 在客户端上执行此操作,那么您 应该:
Set the lang attribute on each piece of content (or wrapper `s). Grab the language from navigator.language or navigator.userLanguage (check them both, the latter is for IE, the first is, AFAIK, everyone else) and have a suitable default in hand just in case. Then show everything whose lang matches the language and hide everything whose lang doesn't match. For example, if you have this HTML:
<div lang="en" class="wrapper">
<h1>English</h1>
<p>Here is some English content.</p> </div> <div lang="fr" class="wrapper" style="display: none;">
<h1>Française</h1>
<p>Voici le contenu en français.</p> </div> <div lang="pt" class="wrapper" style="display: none;">
<h1>Português</h1>
<p>Aqui você encontra o conteúdo Português.</p> </div> And then some JavaScript (I'll use jQuery as that's my weapon choice)
> $(document).ready(function() {
> var known = { en: true, fr: true, pt: true };
> var lang = (navigator.language || navigator.userLanguage || 'en').substr(0, 2);
> if(!known[lang])
> lang = 'en';
> // Find all <div>s with a class of "wrapper" and lang attribute equal to `lang`
> // and make them visibile.
> $('div.wrapper[lang=' + lang + ']').show();
> // Find all <div>s with a class of "wrapper" and lang attribute not equal
> // to `lang` and make them invisibile.
> $('div.wrapper[lang!=' + lang + ']').hide(); });
这是一个活生生的例子:http://jsfiddle.net/ambiguous/hDM3T/2/
如果您将显示/隐藏逻辑保留在一个单独的函数中,该函数需要 语言参数,那么提供一种语言就很容易了 也有某种选择小部件。
如果这样更容易工作,您也可以使用该语言的类 使用您的 JavaScript 工具,但保留 lang 属性 会是个好主意。
【问题讨论】:
-
所以每种语言都有很多开销,只是隐藏/显示数据?