【轉】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')); } }); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM