使用jquery-i18n-properties实现多语言切换,自动选择,及持久化
国际化英文单词为:Internationalization,又称i18n,“i”为单词的第一个字母,“18”为“i”和“n”之间单词的个数,而“n”代表这个单词的最后一个字母。jQuery.i18n.properties采用.properties文件对JavaScript进行国际化。jQuery.i18n.properties插件首先加载默认的资源文件(strings.properties),然后加载针对特定语言环境的资源文件(strings_zh.properties),这就保证了在未提供某种语言的翻译时,默认值始终有效。
官方地址:https://code.google.com/archive/p/jquery-i18n-properties/
官方github地址:https://github.com/jquery-i18n-properties/jquery-i18n-properties
实现步骤,
第一步:下载JS插件
jquery.i18n.properties.js
第二步
编写前端页面
<select id="lang" class=" form-control">
<option value="zh-CN">中文</option>
<option value="en">English</option>
</select>
<label data-locale="username">用户名:</label><input type="text">
<label data-locale="password">密码:</label><input type="password">
编写JS
loadProperties();
function loadProperties() {jQuery.i18n.properties({ //加载资浏览器语言对应的资源文件
name: "strings", //属性文件名 命名格式: 文件名_国家代号.properties
path: "i18n/", //注意这里路径是你属性文件的所在文件夹
mode: "map", //用Map的方式使用资源文件中的值
//language: "zh", //国家代号 name+language刚好组成属性文件名:strings+zh -> strings_zh.properties
//删除则自动选择浏览器语言
callback: function() {
$("[data-l ocale]").each(function() {
//console.log($(this).data("locale"));
$(this).html($.i18n.prop($(this).data("locale")));
});
}
});
}
持久化
$(function() {
if(!localStorage.currentLang) {
//本地存储当前选中语言
localStorage.currentLang = $("#lang option:selected").val();
} else {
//定义当前语言
var currLang = localStorage.currentLang;
$("#lang option[value=" + currLang + "]").attr("selected", true);
$("#lang").on("change", function() {
//存储当前选中的语言
localStorage.currentLang = $(this).children("option:selected").val();
//单页面可以注释
//刷新
location.reload();
loadProperties(localStorage.currentLang);
});
}
loadProperties(localStorage.currentLang)
});
function loadProperties(currentLang) {
switch(currentLang) {
case "en":
langi18n = "en";
break;
case "zh":
langi18n = "zh";
break;
default:
langi18n = "zh";
}
jQuery.i18n.properties({ //加载资浏览器语言对应的资源文件
name: "strings", //属性文件名 命名格式: 文件名_国家代号.properties
path: "i18n/", //注意这里路径是你属性文件的所在文件夹
mode: "map", //用Map的方式使用资源文件中的值
language: langi18n, //国家代号 name+language刚好组成属性文件名:strings+zh -> strings_zh.properties
//删除则自动选择浏览器语言
callback: function() {
$("[data-i18n]").each(function() {
$(this).html($.i18n.prop($(this).data("i18n")));
//特殊标签处理
$(this).attr("placeholder", $.i18n.prop($(this).attr("data-i18n")));
});
}
});
}
编写语言包
strings_en.properties
username=NAME
password=PASSWORD
strings_zh.properties
username=用户名
password=密码
注,请在服务器中打开。
下载地址
http://download.csdn.net/download/u013317712/10247518
- 上一篇:没有了
- 下一篇:没有了