使用下面描述的脚本,我想知道是否有办法在页面上放置链接以允许用户在页面加载后更改显示的语言。最初,它显示用户的默认语言,但我想允许他们动态更改它。
谢谢!
托马斯
通常的方法是将语言分开(例如,每种语言一个 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 属性将是一个好主意。