使用jquery.i18n.properties.js实现js国际化

[url]http://my.oschina.net/u/871551/blog/422799[/url]
js国际化的框架jquery.i18n.properties.js,用了一些还是比较方便的。

首先引入js文件,这个框架是依赖jquery的,所以jquery也要先引入,由于项目用了requireJs,所以在main文件里引入一下就可以了
require.config({
baseUrl: contextPath + "/js",
paths: {
jquery: 'util/jquery-1.9.1',
jqueryi18n: 'util/jquery.i18n.properties'
},
shim: {
'jquery': {
exports: '$'
},
'jqueryi18n': {
deps: [ "jquery" ],
exports: 'jqueryi18n'
}
}
});

其次在资源文件目录下建立一个文件夹放properties文件
[img]http://static.oschina.net/uploads/space/2015/0531/092452_B9Ey_871551.png[/img]


由于系统可以手动切换语言,所以把语言设置写道cookie里面,
var setLanguageCookie = function (language) {
var d = new Date();
d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = "language=" + escape(language) + "; " + expires + "; path=/";
};

调用jquery.i18n.properties.js的$.i18n.properties()方法。如果cookie里有语言的设置就用cookie里的,如果没有就用浏览器的语言。
var lan = navigator.language || navigator.userLanguage;
var arrStr = document.cookie.split("; ");
for (var i = 0; i < arrStr.length; i++) {
var temp = arrStr[i].split("=");
if (temp[0] == 'language') {
lan = unescape(temp[1]);
}
}
$.i18n.properties({
name: 'message',
path: contextPath + '/i18n/',
mode: 'map',
language: lan
});

用Spring的记得把i18n这个资源目录加到配置文件里面
<mvc:resources mapping="/i18n/**" location="/resources/i18n/"/>

使用CookieLocaleResolver来读取cookie的值,配置一下cookieName
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="language"/>
</bean>

在message_en.properties和message_zh.properties里面写入key:site.success
[color=darkblue]site.success=Success!
site.success=成功![/color]
以上这些配置好了之后就可以使用了,调用$.i18n.prop(key)来显示不同语言的提示
alert($.i18n.prop('site.success'));

英文环境下:
[img]http://static.oschina.net/uploads/space/2015/0531/093831_zklu_871551.png[/img]


中文环境下:
[img]http://static.oschina.net/uploads/space/2015/0531/093832_6qgy_871551.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值