這個能夠點擊菜單進行中英文切換,每次切換就能夠改變sessionStorage.languge,進行改變i18n的參數lang的值,而後從新調用下就能夠了。javascript
工程結構:css
i18n--|html
|---css(這裏是空的)java
|--img(這裏是空的)jquery
|--js--|瀏覽器
|--i18n--|緩存
|--messages_en_US.properties//國家化翻譯文件session
|--messages_en.properties//國家化翻譯文件函數
|--messages_zh_CN.properties//國家化翻譯文件this
|--messages_zh.properties//國家化翻譯文件
|--messages.properties//國家化翻譯文件
|--jquery.i18n.properties.js//i18n插件
|--jquery-3.2.1.min.js
|--index.html
其中,index.html裏邊的代碼是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src='js/jquery-3.2.1.min.js' type="text/javascript"></script>
<script src='js/jquery.i18n.properties.js' type="text/javascript"></script>
</head>
<body>
<span data-i18n="common.test"></span>
<script>
function loadProperties(name,path,lang){
var lang=lang || navigator.languge//沒有傳人語言時候,就用瀏覽器緩存的
$.i18n.properties({
name:name,//這個是參數path指定路徑的首個單詞,也就是資源文件名
path:path,//指定國際化映射文件的路徑
mode:'map',//指定以鍵值對的形式獲取資源
languge:lang,//指定語言類型中英文,舉個例子:"zh_CN"爲中文
callback:function(){//加載完成後的回調函數
$('[data-i18n]').each(function(){//遍歷全部屬性是data-i18n
$(this).html($.i18n.prop($(this).data("i18n")));//把這個屬性值傳入翻譯後放到頁面上
})
$('[data-i18n]').each(function(){//遍歷全部屬性是data-i18n
$(this).attr('placeholder',$.i18n.prop($(this).data("i18n")));//翻譯placeholder屬性值
})
}
})
}
var i18n=function(key){
return $.i18n.prop(key);
}
$(document).ready(function(){
loadProperties('messages','js/i18n/','zh_CN');//調用國際化函數
console.log(i18n("common.test"));//也能夠直接在js裏邊定義以後調用翻譯
})
</script>
</body>
</html>
messages_zh.properties文件內容是:
common.test=\u5220\u9664\u4E91\u684C\u9762