使用下面描述的脚本,我想知道是否有办法在页面上放置一个链接,以允许用户在页面加载后更改显示的语言。最初,它显示用户的默认语言,但我想允许他们改变它,如果他们想要动态的。
谢谢!
托马斯
通常的方法是将语言分开(一个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/
如果你将show / hide逻辑保存在一个单独的函数中 语言参数那么提供一种语言会很容易 某种选择小部件。
如果语言更容易使用,您也可以使用该语言 使用您的JavaScript工具,但保留lang属性 会是一个好主意。
答案 0 :(得分:0)
你应该使用模板引擎(你也可以使用JSON):
http://www.jquery4u.com/javascript/10-javascript-jquery-templates-engines/
jQuery templating engines
What Javascript Template Engines you recommend?
http://garann.github.io/template-chooser/
http://microjs.com/#templating
Good Javascript template engine to work with JSON
http://tempojs.com/
但是要回答你的问题,这是解决方案:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function setLanguage(lang) {
var known = { en: true, fr: true, pt: true };
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();
};
</script>
<a href="javascript:void(0)" onclick="setLanguage('fr')">fr</a>