1 基本介紹
jquery與i18next配合基於json數據格式實現國際化,而jquery與jquery.i18n.properties配合基於鍵值對數據格式實現國際化。
個人推薦使用i18next實現國際化,它有較詳細的開發文檔,並且是基於json的數據格式。
I18next的官網:https://www.i18next.com/
注意:(1)一定要注意jquery的版本和i18next的版本問題。
(2)resGetPath:'./js/language/locales/__lng__/__ns__.json’代表的意思是“./js/language/locales/en/translation.json”或者“./js/language/locales/zh/translation.json”。
下圖是本文的i18next整體配置結構,也可從github上下載:https://github.com/MasonYyp/jquery_i18next.git
2 源代碼及實現
2.1 結果截圖
2.2 js源代碼
main()
function main(){
test();
}
function test(){
$("#en").click(function(){
update_en_language();
});
$("#zh").click(function(){
update_zh_language();
})
}
function update_en_language(){
$.i18n.init({
lng: 'en',
resGetPath : './js/language/locales/__lng__/__ns__.json'
}, function(err, t){
$("#henu").text($.i18n.t('message'))
});
}
function update_zh_language(){
$.i18n.init({
lng: 'zh',
resGetPath : './js/language/locales/__lng__/__ns__.json'
}, function(err, t){
$("#henu").text($.i18n.t('message'))
});
}
2.3 html源代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="js/libs/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/libs/i18next-1.6.3.min.js"></script>
<script type="text/javascript" src="js/language/configure_i8n.js"></script>
</head>
<body>
<button id="zh">中文</button>
<button id="en">English</button>
<div id="henu">河南大學</div>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>