关于国际化一个简单应用,写在这里记住,直接贴代码。
新建HTML页面,引入jquery 和 jquery.properties.js。
<!--引入资源-->
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="i18n/jquery.i18n.properties.js"></script>
要准备切换的资源:
<div class="">
<b class="i18n" id="usernameText">用户名</b>:<input type="text" class="i18n" id="username" placeholder="请输入用户名" ><br/>
<b class="i18n" id="passwordText">密码</b>:<input type="password" class="i18n" id="password" /><br/>
<button onclick="loadProperties()">切换</button>
<button onclick="alertFun()">弹出框提示</button>
</div>
这里通过点击按钮"切换"来实现中英文的切换。实际上在开发过程中应该读取浏览器的当前语言来进行切换。
再接着建立资源文件,先建立文件夹i18n,接着继续建立文件夹locate,下面建立两个文件:en_properties和zh_CN.properties。
en_properties:
index_username_placeholder = please input username
index_usernameTextText = username
index_passwordTextText = password
MessageSuccess = operatie success
zh_CN.properties:
index_username_placeholder = 请输入用户名
index_usernameTextText = 用户名
index_passwordTextText = 密码
MessageSuccess = 操作成功
目录:
最后用js代码来实现上面的逻辑:
//首先进行初始化操作 应该和浏览器语言保持一致,这里默认中文
$(function(){
loadProperties();
})
var language = 'zh_CN';
function loadProperties(){
$.i18n.properties({
name : language,//资源文件名称
path:'i18n/locale/',//资源所在的路径
mode:'map',//用Map的方式使用资源文件中的值
callback:function(){//加载成功后设置显示内容
if(language == "en"){
language = 'zh_CN';
}
else{
language = 'en';
}
//手动一个一个展示
// $("#username").attr("placeholder",$.i18n.prop('index_username_placeholder'));
// $("#usernameText").text($.i18n.prop('index_usernameTextText'));
// $("#passwordText").text($.i18n.prop('index_passwordTextText'));
//以遍历的方式进行 创建相应的规则 key和ID结合 谨慎使用
//控制文本
$(".i18n").each(function (index,e) {
$(this).text($.i18n.prop('index_' + this.id + "Text"));
});
//控制placeholder
$(".i18n").each(function (index,e) {
//判断是否存在该属性 如果存在就赋值
if((typeof($(this).attr("placeholder")) != "undefined")){
$(this).attr("placeholder",$.i18n.prop('index_' + $(this).attr("id") + "_placeholder"));
}
});
}
})
}
function alertFun(){
alert($.i18n.prop("MessageSuccess"));
}