纯js国际化(i18n)

i18n,是internationalization单词的简写,中间18个字符略去,简称i18n,意图就是实现国际化,方便产品在不同的场景下使用

目标:可以点击切换语言或者ChangeLanguage的按钮 来完成英语和中文的切换

效果图如下:

纯js国际化(i18n)

纯js国际化(i18n)

实现方案:https://github.com/jquery-i18n-properties/jquery-i18n-properties

实现过程:

步骤一:代码结构

纯js国际化(i18n)

步骤2:实现html文件

 <html lang="en">

 <head>
<meta charset="UTF-8">
<title>国际化</title>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.i18n.properties.min.js"></script>
</head> <body> <label data-locale="User Name">用户名:</label><input type="text">
<label data-locale="Password">密码:</label><input type="password">
<button id='btn' data-locale="Btn Change">切换语言</button> <script type="text/javascript">
isEng = true
btn.onclick=function(){
if(!isEng){
loadProperties('en');
}else{
loadProperties('zh');
}
isEng = !isEng }
function loadProperties(lang) {
$.i18n.properties({
name: 'strings', //属性文件名 命名格式: 文件名_国家代号.properties
path: 'i18n/', //注意这里路径是你属性文件的所在文件夹
mode: 'map',
language: lang, //这就是国家代号 name+language刚好组成属性文件名:strings+zh -> strings_zh.properties
callback: function () {
$("[data-locale]").each(function () {
console.log($(this).data("locale"));
$(this).html($.i18n.prop($(this).data("locale"))); });
}
});
}
loadProperties('en'); </script>
</body> </html>

纯js国际化(i18n)

纯js国际化(i18n)

核心思路:

既然要做国际化,我们得准备在不同语言情况下的词汇

将中英文的一些词汇和描述消息 放在i18n的文件夹中的strings_en.properties和strings_zh.properties

那么如果是中文环境,就按照strings_zh.properties这个文件中的词汇描述来;否则按照英文的来

这样一来,不同语言环境就可以加载不同的词汇了,国际化完毕

代码打包放在百度云了,希望能帮到更多的人:

https://pan.baidu.com/s/1Dl6jup_Igw9QHj9N2EQsSg

上一篇:阿里八八Alpha阶段Scrum(5/12)


下一篇:正则表达式split匹配多种例如 “】”,“,”两种(页面级中英文切换方案)