【转】i18n实现前端国际化(实例)

源地址:https://www.jianshu.com/p/ea93efef5155

i18n实现前端国际化(实例)

0.1442018.08.27 16:25:10字数 246阅读 10563
在今日的需求中需要利用 i18n 这个框架来实现前端的国家化操作,下图是实现效果:

点击选择框实现网页上语言的切换:

 
 

下面开始实现过程:

  1. 所需工具:
    - jquery-3.3.1.js 下载地址:jquery
    - jquery.i18n.properties.js jquery.i18n.properties.js
  2. 搭建项目目录如下:
     

    其中:language.js 为自定义的 js 文件,用于实现页面逻辑,strings_en_US.properties
    和 strings_en_ZH.properties文件为语言文件。
  3. 首先我们在 index.html 中写上一定的测试页面代码,如下所示:
<!doctype html>  
<head>  
 <meta charset="UTF-8">  
 <meta name="viewport"  
  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  
 <meta http-equiv="X-UA-Compatible" content="ie=edge">  
 <title>国际化样例</title>  
</head>  
<body>  
  
<form>  
     <select class="lan_select">  
         <option class="lan_zh">中文</option>  
         <option class="lan_en">英文</option>  
     </select>
 </form>  
  
<label class="username"><!--用户名:--></label><input type="text">  
<label class="password"><!--密码:--></label><input type="password">  
  
<script type="application/javascript" src="JS/jquery-3.3.1.js"></script>  
<script type="application/javascript" src="JS/jquery.i18n.properties.js"></script>  
<script type="application/javascript" src="JS/language.js"></script>  
  
</body>  
</html>
  1. 下面我们在两个语言中分别定义需要显示的文字:
    1. strings_en_ZH.properties文件:
      username=用户名:  
      password=密码: 
      lan_zh=中文  
      lan_en=英文
      
    2. strings_en_US.properties 文件:
      username=User Name:  
      password=Password:  
      lan_zh=Chinese  
      lan_en=English
      
  2. 最后我们在 language.js 中实现点击事件和切换方法,代码如下:
var LANGUAGE_Index = "zh_CN"; //标识语言  
  
jQuery(document).ready(function () {  
    // alert("页面加载时调用的方法");  
  
  LANGUAGE_Index = jQuery.i18n.normaliseLanguageCode({}); //获取浏览器的语言  
  loadProperties(LANGUAGE_Index);  
});  
  
  
$(".lan_select").change(function () {  
  
  
    if (($(".lan_select").val() === "英文") || ($(".lan_select").val() === "English")) {  
        LANGUAGE_Index = "en_US";  
  } else {  
        LANGUAGE_Index = "zh_CN";  
  }  
  
    loadProperties(LANGUAGE_Index);  
  
});  
  
  
function loadProperties(type) {  
    jQuery.i18n.properties({  
        name: 'strings', // 资源文件名称  
        path: 'Languages/', // 资源文件所在目录路径  
        mode: 'map', // 模式:变量或 Map  
        language: type, // 对应的语言  
        cache: false,  
        encoding: 'UTF-8',  
        callback: function () { // 回调方法  
            $('.lan_zh').html($.i18n.prop('lan_zh'));  
            $('.lan_en').html($.i18n.prop('lan_en'));  
            $('.username').html($.i18n.prop('username'));  
            $('.password').html($.i18n.prop('password'));  
        }  
    });  
}
posted on 2019-09-25 10:21  海子呢  阅读(4857)  评论(0编辑  收藏  举报