第一步:导入插件
<script src="js/langSwitch.js" type="text/javascript"></script>
插件内容:
(function () {
if($.cookie("lang") != null) return;
var lang = navigator.language || navigator.userLanguage;//常规浏览器语言和IE浏览器
var briefLang = lang.substr(0, 2);//截取lang前2位字符
switch (briefLang) {
case 'zh':
$.cookie("lang", "cn");
break;
case 'en':
default:
$.cookie("lang", "en");
}
})();
(function () {
var language = null;
var curLang = $.cookie("lang");
$().localize("langSwitch",
{
pathPrefix: "resources/lang",
language: curLang,
callback: function(data, defaultCallback){
language = data;
}
});
var langSwitchBar = $(".dropdown-language");
var topLang = $('<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"></a>');
topLang.append($('<img alt="">').attr("src", "theme/assets/global/img/flags/" + language.Img[curLang] + ".png"));
topLang.append($('<span class="langname"></span>').text(language.curLang));
topLang.append($('<i class="fa fa-angle-down"></i>'));
langSwitchBar.append(topLang);
var langList = $('<ul class="dropdown-menu dropdown-menu-default"></ul>');
var getLangListItem = (function () {
var template = $('<li><a href="javascript:;"></a></li>');
return function (code, des, imgCode) {
var result = template.clone();
result.attr("data-lang", code);
var a = result.find("a");
a.append('<img alt="" src="theme/assets/global/img/flags/' + imgCode + '.png">');
a.append(des);
result.on("click", function ()
{
$.cookie("lang", $(this).attr("data-lang"));
location.reload();
});
return result;
}
})();
for(var code in language.LangList)
{
langList.append(getLangListItem(code, language.LangList[code], language.Img[code]));
}
langSwitchBar.append(langList);
})();
第二步:在标签上添加data-localize属性
<span data-localize="html.text"></span>
第三步:创建一个目录为resources\lang,在里面放json文件
中文部分:
英文部分:
第四步:调用json文件的内容渲染到页面上
var langConfig = {
pathPrefix: "resources/lang",
language: 'cn'
};
$("[data-localize]").localize("sidebarMenu", langConfig).localize("headerMenu", langConfig).localize("aaa", langConfig);
扩展:js部分如alert的内容如何国际化
var language = "";//语言翻译包数据
//获取语言包
var setLanguage = function () {
$().localize("aaa",
{
pathPrefix: "resources/lang",
language: 'cn',
callback: function (data, defaultCallback) {
language = data;
}
});
}