Javascript 在我的情况下,如何本地化一个简单的 HTML 网站页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7530401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:37:12  来源:igfitidea点击:

How to localize a simple HTML website page in my case?

javascriptjqueryhtml

提问by Leem.fin

I am NOTdeveloping any web service application which contain clientside and backend serverside (like java EE application or Ruby on Rails).

没有开发任何包含客户端和后端服务器端的Web 服务应用程序(如 java EE 应用程序或 Ruby on Rails)。

Instead, I am simply developing a HTML website page, on this page, there are two flag images(USA and China) which is used as a language selection of the page for users.

相反,我只是在开发一个 HTML网站页面,在这个页面上,有两个标志图像(美国和china),用作用户页面的语言选择。

I am wondering, for this single web page development (without any backend system), is there any efficient way to implement the page localization(that's display the page in different language) based on the flag selection from user?

我想知道,对于这个单一的网页开发(没有任何后端系统),是否有任何有效的方法可以根据用户的标志选择来实现页面本地化(即以不同的语言显示页面)?

回答by ceving

You can use the standard HTML langattribute:

您可以使用标准的 HTMLlang属性:

<span lang="en">Scale</span><span lang="de">Ma?stab</span>

And then you can hide and show the matching elements:

然后你可以隐藏和显示匹配的元素:

function select_language(language) {
    $("[lang]").each(function () {
        if ($(this).attr("lang") == language)
            $(this).show();
        else
            $(this).hide();
    });
}

I use a simple selection:

我使用一个简单的选择:

<select onchange="select_language(this.options[this.selectedIndex].value)">
  <option value="en" selected>English</option>
  <option value="de">Deutsch</option>
</select>

回答by ceving

Nowadays I would do it without jQuery. First I would hide all nodes with a langattribute and show only the default language. This can be done in CSS:

现在我会在没有 jQuery 的情况下做到这一点。首先,我会隐藏所有具有lang属性的节点并仅显示默认语言。这可以在 CSS 中完成:

[lang] {
  display: none;
}
[lang=en] {
  display: unset;
}

Without JavaScript enabled the document is not localized but at least readable in the default language.

如果没有启用 JavaScript,文档不会本地化,但至少可以用默认语言读取。

Next I would use some JavaScript to show the correct language, if it is in the list of supported languages.

接下来我将使用一些 JavaScript 来显示正确的语言,如果它在支持的语言列表中。

function localize (language)
{
  if (['de'].includes(language)) {
    let lang = ':lang(' + language + ')';
    let hide = '[lang]:not(' + lang + ')';
    document.querySelectorAll(hide).forEach(function (node) {
      node.style.display = 'none';
    });
    let show = '[lang]' + lang;
    document.querySelectorAll(show).forEach(function (node) {
      node.style.display = 'unset';
    });
  }
}

You can either use a select box or the browser language.

您可以使用选择框或浏览器语言。

localize(window.navigator.language);

回答by graphicdivine

Here's one way around this:

这是解决此问题的一种方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Localise</title>
</head>

<body>

<a href="#china" onclick="showthis('contentchina')">China flag</a>|
<a href="#usa" onclick="showthis('contentusa')">USA flag</a>

<div id="contentchina" style="display:none">
Lorem ipsum dolor sit amet...
</div>

<div id="contentusa" style="display:none">
Duis aute irure dolor...
</div>

<script>
function showthis(nation){
    document.getElementById(nation).style.display="block";
    return false;
}
</script>
</body>
</html>

回答by Tim Büthe

You can use JavaScript to read the user language and show the right flag/content:

您可以使用 JavaScript 来读取用户语言并显示正确的标志/内容:

HTML:

HTML:

<img id="myFlag" src="flag_default.png"/>

and some jQuery (since you tagged your question with jQuery):

和一些 jQuery(因为你用 jQuery 标记了你的问题):

var supportedLangs = ['de', 'en', 'cn'];
var userLang = navigator.language;

if($.inArray(userLang, supportedLangs) >= 0){
    $('myFlag').attr('src', 'flag_' + userLang + '.png');
}

hjsfiddle

hjsfiddle

回答by thedaian

Easy answer: No, using a backend is the easiest and best way to accomplish this. Backend code is designed for dynamic content, which is what you want.

简单的回答:不,使用后端是实现这一目标的最简单和最好的方法。后端代码专为动态内容而设计,这正是您想要的。

Hard answer: This is a way to do this without dividing up your pages into two directories. The problem is that you're going to have to use Javascript to generate your page content, and that's generally a bad idea. But you could use a javascript MVC library, plus ajax calls to content folders that pull in the text (you'd still have to have two directories for English and Chinese, but they would only contain content, not HTML). The thing is, there's multiple potential problems with this method that it's only worth using if you knowyour users will have a modern browser with javascript enabled.

硬性回答:这是一种无需将页面分成两个目录即可完成此操作的方法。问题是您将不得不使用 Javascript 来生成您的页面内容,这通常是一个坏主意。但是你可以使用一个 javascript MVC 库,加上对拉入文本的内容文件夹的 ajax 调用(你仍然必须有两个英文和中文目录,但它们只包含内容,而不是 HTML)。问题是,这种方法存在多个潜在问题,只有在您知道您的用户将拥有启用了 javascript 的现代浏览器时才值得使用。

回答by Derek Adair

I would suggest looking into a template engine for this problem. To me it's not exactlya backendbut more of a grey area. Something like MoustacheOR smartywould be perfect for you.

我建议为这个问题寻找一个模板引擎。对我来说,这不完全backend一个灰色区域,而是更多的灰色区域。像MustacheOR smarty这样的东西对你来说是完美的。

Simply put, i agree with the other posters that this is not reasonable to achieve on the client side.

简而言之,我同意其他海报,即在客户端实现这是不合理的。

回答by WebDev-SysAdmin

Your webpage needs to understand what encoding it should be using when rendering Chinese characters:

你的网页需要了解它在渲染汉字时应该使用什么编码:

 <! -- NOTICE THE "charset=UTF-8" !!!! -->
<head>    
    <meta content="text/html; charset=UTF-8" http-equiv="content-type"/>
</head>

回答by chendianbuji

I read ceving's answer, and then write a JS library languages.jsto do this.

我阅读了ceving的回答,然后编写了一个JS库languages.js来做到这一点。

I change the sequence of <title>s' with different languages, so it works if you want to switch lang in the page title.

<title>用不同的语言改变了s'的顺序,所以如果你想在页面标题中切换 lang,它就可以工作。

Write HTML like this:

像这样编写 HTML:

<html>
  <head>
    <title lang="en">Test Page</title>
    <title lang="zh-cmn-Hans">测试页面</title>
    <title lang="ja">テストページ</title>
    <title lang="miaw">miaw miaw miaw</title>
  </head>
  <body>
    <div lang="en" style="display:block;">Why does the sun rise? Why does the moon shine?</div>
    <div lang="zh-cmn-Hans">太阳为什么会升起?月亮为什么会发光?</div>
    <div lang="ja" style="display:inline">太陽はなんで昇る?月はなぜ輝く?</div>
    <div lang="miaw" style="display:inline">miaw miaw miaw miaw miaw miaw miaw miaw miaw miaw miaw miaw miaw</div>
  </body>
</html>
<script src="https://raw.githubusercontent.com/MuromiU/JS/master/src/languages.js"></script>

Usage:

用法:

Languages.select(lang);

More detail: github readme

更多细节: github自述文件

回答by Vimal Mohan

Generally JS generating the code for you is not good. But, I did one POC for the same using underscore.js. The framework is having an "_template" function that helps us to replace all the keys in the HTML file. The function accepts the key value pair in JSON format.

一般JS为你生成代码是不好的。但是,我使用underscore.js做了一个 POC 。该框架有一个“_template”函数,可以帮助我们替换 HTML 文件中的所有键。该函数接受 JSON 格式的键值对。

Based on the language selected, load the corresponding JSON file and then pass it on to the _template function. This will replace all the keys.

根据选择的语言,加载相应的 JSON 文件,然后将其传递给 _template 函数。这将替换所有键。

回答by John Hartsock

Yes this is possible. Here is one way

是的,这是可能的。这是一种方法

Structure you HTML like this in your folders

在你的文件夹中像这样构造你的 HTML

/root
  /Chinese
  /English-American
  index.html

The root folder would contain your page with the language selection and the Chinese and English-American will contain your language specific pages.

根文件夹将包含您的带有语言选择的页面,而中文和英美将包含您的特定语言页面。

Now on index.html simply direct the user to the correct language folder and all links will reference the correct language folder

现在在 index.html 上只需将用户定向到正确的语言文件夹,所有链接都将引用正确的语言文件夹