在今日的需求中需要利用 i18n 這個(gè)框架來(lái)實(shí)現(xiàn)前端的國(guó)家化操作,下圖是實(shí)現(xiàn)效果:
點(diǎn)擊選擇框?qū)崿F(xiàn)網(wǎng)頁(yè)上語(yǔ)言的切換:
下面開(kāi)始實(shí)現(xiàn)過(guò)程:
- 所需工具:
- jquery-3.3.1.js 下載地址:jquery
- jquery.i18n.properties.js jquery.i18n.properties.js - 搭建項(xiàng)目目錄如下:
其中:language.js
為自定義的js
文件莲祸,用于實(shí)現(xiàn)頁(yè)面邏輯其障,strings_en_US.properties
和strings_en_ZH.properties
文件為語(yǔ)言文件亩进。 - 首先我們?cè)?
index.html
中寫(xiě)上一定的測(cè)試頁(yè)面代碼器罐,如下所示:
<!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>國(guó)際化樣例</title>
</head>
<body>
<form>
<select class="lan_select">
<option class="lan_zh">中文</option>
<option class="lan_en">英文</option>
</select>
</form>
<label class="username"><!--用戶(hù)名:--></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>
- 下面我們?cè)趦蓚€(gè)語(yǔ)言中分別定義需要顯示的文字:
-
strings_en_ZH.properties
文件:username=用戶(hù)名: password=密碼: lan_zh=中文 lan_en=英文
-
strings_en_US.properties
文件:username=User Name: password=Password: lan_zh=Chinese lan_en=English
-
- 最后我們?cè)?
language.js
中實(shí)現(xiàn)點(diǎn)擊事件和切換方法跟束,代碼如下:
var LANGUAGE_Index = "zh_CN"; //標(biāo)識(shí)語(yǔ)言
jQuery(document).ready(function () {
// alert("頁(yè)面加載時(shí)調(diào)用的方法");
LANGUAGE_Index = jQuery.i18n.normaliseLanguageCode({}); //獲取瀏覽器的語(yǔ)言
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', // 資源文件名稱(chēng)
path: 'Languages/', // 資源文件所在目錄路徑
mode: 'map', // 模式:變量或 Map
language: type, // 對(duì)應(yīng)的語(yǔ)言
cache: false,
encoding: 'UTF-8',
callback: function () { // 回調(diào)方法
$('.lan_zh').html($.i18n.prop('lan_zh'));
$('.lan_en').html($.i18n.prop('lan_en'));
$('.username').html($.i18n.prop('username'));
$('.password').html($.i18n.prop('password'));
}
});
}