i18n国际化的例子

这个可以点击菜单进行中英文切换,每次切换就可以改变sessionStorage.languge,进行改变i18n的参数lang的值,然后重新调用下就可以了。

工程结构:

i18n--|

         |---css(这里是空的)

         |--img(这里是空的)

         |--js--|

                 |--i18n--|

                              |--messages_en_US.properties//国家化翻译文件

                              |--messages_en.properties//国家化翻译文件

                              |--messages_zh_CN.properties//国家化翻译文件

                              |--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

 

posted @ 2017-09-28 16:48  sweeeper  阅读(1039)  评论(0编辑  收藏  举报