首页 > Web开发 > 详细

纯js国际化(i18n)

时间:2019-05-15 12:51:17      阅读:174      评论:0      收藏:0      [点我收藏+]

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

 

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

效果图如下:

技术分享图片

技术分享图片

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

 

 实现过程:

步骤一:代码结构

技术分享图片

 

 

 步骤2:实现html文件

 1 <html lang="en">
 2 
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>国际化</title>
 6     <script src="js/jquery.min.js"></script>
 7     <script src="js/jquery.i18n.properties.min.js"></script>
 8 </head>
 9 
10 <body>
11 
12     <label data-locale="User Name">用户名:</label><input type="text">
13     <label data-locale="Password">密码:</label><input type="password">
14     <button id=‘btn‘ data-locale="Btn Change">切换语言</button>
15 
16     <script type="text/javascript">
17         isEng = true
18         btn.onclick=function(){
19             if(!isEng){
20                 loadProperties(en);
21             }else{
22                 loadProperties(zh);
23             }
24             isEng = !isEng
25             
26         }
27         function loadProperties(lang) {
28             $.i18n.properties({
29                 name: strings,    //属性文件名     命名格式: 文件名_国家代号.properties
30                 path: i18n/,   //注意这里路径是你属性文件的所在文件夹
31                 mode: map,
32                 language: lang,     //这就是国家代号 name+language刚好组成属性文件名:strings+zh -> strings_zh.properties
33                 callback: function () {
34                     $("[data-locale]").each(function () {
35                         console.log($(this).data("locale"));
36                         $(this).html($.i18n.prop($(this).data("locale")));
37 
38                     });
39                 }
40             });
41         }  
42         loadProperties(en);
43         
44         
45     </script>
46 </body>
47 
48 </html>

 技术分享图片

 

 技术分享图片

 

 核心思路:

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

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

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

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

 

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

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

 

 

 

 

 

纯js国际化(i18n)

原文:https://www.cnblogs.com/kunyashaw/p/10868746.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!