web前端页面jQuery语言国际化,实现中英切换

   2019-06-02 1470
核心提示:之前web项目一直都是中文为主的,现在随着业务的需求,需要将网站语言支持多语言,这个着实给不管是前台还是后台都增加了不小的

之前web项目一直都是中文为主的,现在随着业务的需求,需要将网站语言支持多语言,这个着实给不管是前台还是后台都增加了不小的挑战,因为之前做的时候根本没有考虑多语言的问题,导致很多页面写的不是很灵活,样式写的比较死,中文看起来不错,其他语言又比较难看,其他语言看起来不错,中文比较难看,总之调了很久才能好。

今天,主要弄一下基于jQuery.i18n.properties 实现前端页面的资源国际化这个问题,也就是将页面中的显示中文的地方都变成可以根据用户选择的语言来变化的。网上也有很多js专门做这个国际化的,好终我们选择了jQuery.i18n.properties来实现。

先来copy一段关于jQuery.i18n.properties 的说明哈。

jQuery.i18n.properties是一款轻量级的jQuery国际化插件,能实现Web前端的国际化。
国际化英文单词为:Internationalization,又称i18n,“i”为单词的第一个字母,“18”为“i”和“n”之间单词的个数,而“n”代表这个单词的好后一个字母。jQuery.i18n.properties采用.properties文件对Javascript进行国际化。jQuery.i18n.properties插件首先加载默认的资源文件(strings.properties),然后加载针对特定语言环境的资源文件(strings_zh.properties),这就保证了在未提供某种语言的翻译时,默认值始终有效。

废话少说,直接上代码吧(just demo)!

第一步:
下载必须的js文件
jquery.i18n.properties.js
jquery.js

第二步:
新建demo静态页面index.html

中文简体 中文繁體 English




<script src="js/jquery.js"></script>        
<!-- 加载语言包文件 -->
<script src="js/jquery.i18n.properties-min-1.0.9.js"></script>
<script src="js/language.js"></script>
  • 1
  • 2
  • 3
  • 4

说明:
1、meta id=”i18n_pagename” content=”index-common” 这里面的index-common写法,这里是引 入了两个资源文件index和common,这样做的好处就是,我们可以把公用部分的资源文件放到common里面,例如页头,页脚等,而且不需在每个页面都复制这部分内容,当共有内容有所变化,只需要修改common.properties就可以全部修改啦。
2、获取方式一:label class=”i18n” name=”hellomsg1”这里面class=”i18n”写法,下边在js里面我们可以根据类选择器获取需要国际化的地方,然后name=”hellomsg1”这里面的hellomsg1跟资源文件里面的key保持一致。获取方式二:input type=”search” class=”i18n-input” selectname=”searchPlaceholder” selectattr=”placeholder”这里面的class=”i18n-input”写法,跟上边的区别就是可以给html标签的任何属性可以赋值,例如placeholder,name,id什么的都可以,selectattr=”placeholder”里面的placeholder就是要赋值的属性,selectname=”searchPlaceholder”里面的searchPlaceholder跟资源文件里面的key保持一致。

第三步:
配置language.js文件


var getcookie = function(name, value, options) {
if (typeof value != ‘undefined’) { // name and value given, set cookie
options = options || {};
if (value === null) {
value = ‘’;
options.expires = -1;
}
var expires = ‘’;
if (options.expires && (typeof options.expires == ‘number’ || options.expires.toUTCString)) {
var date;
if (typeof options.expires == ‘number’) {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = ‘; expires=’ + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? ‘; path=’ + options.path : ‘’;
var domain = options.domain ? ‘; domain=’ + options.domain : ‘’;
var s = [cookie, expires, path, domain, secure].join(’’);
var secure = options.secure ? ‘; secure’ : ‘’;
var c = [name, ‘=’, encodeURIComponent(value)].join(’’);
var cookie = [c, expires, path, domain, secure].join(’’)
document.cookie = cookie;
} else { // only name given, get cookie
var cookievalue = null;
if (document.cookie && document.cookie != ‘’) {
var cookies = document.cookie.split(’;’);
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + ‘=’)) {
cookievalue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookievalue;
}
};


var getNavLanguage = function(){
if(navigator.appName == “Netscape”){
var navLanguage = navigator.language;
return navLanguage.substr(0,2);
}
return false;
}


var i18nLanguage = “zh-CN”;


var webLanguage = [‘zh-CN’, ‘zh-TW’, ‘en’];


if (getcookie(“userLanguage”)) {
i18nLanguage = getcookie(“userLanguage”);
} else {
// 获取浏览器语言
var navLanguage = getNavLanguage();
if (navLanguage) {
// 判断是否在网站支持语言数组里
var charSize = KaTeX parse error: Expected 'EOF', got '}' at position 223: … }; }̲ else{ ….i18n == undefined) {
console.log(“请引入i18n js 文件”)
return false;
};

 jQuery.i18n.properties({
     name : sourceName, //资源文件名称
     path : 'i18n/' + i18nLanguage +'/', //资源文件路径
     mode : 'map', //用Map的方式使用资源文件中的值
     language : i18nLanguage,
     callback : function() {//加载成功后设置显示内容
         var insertEle = $(".i18n");
         console.log(".i18n 写入中...");
         insertEle.each(function() {
             // 根据i18n元素的 name 获取内容写入
             $(this).html($.i18n.prop($(this).attr('name')));
         });
         console.log("写入完毕");

         console.log(".i18n-input 写入中...");
         var insertInputEle = $(".i18n-input");
         insertInputEle.each(function() {
             var selectAttr = $(this).attr('selectattr');
             if (!selectAttr) {
                 selectAttr = "value";
             };
             $(this).attr(selectAttr, $.i18n.prop($(this).attr('selectname')));
         });
         console.log("写入完毕");
     }
 });
		
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

}

/页面执行加载执行/
$(function(){

execI18n();


$("#language option[value="+i18nLanguage+"]").attr("selected",true);


$("#language").on('change', function() {
    var language = $(this).children('option:selected').val()
    console.log(language);
    getcookie("userLanguage",language,{
        expires: 30,
        path:'/'
    });
    location.reload();
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

});

说明: 这个js文件写的比较详细有注释,大家一看应该就能懂,大致的就是第一次进来时,会根据浏览器的语言选择默认语言,然后用户每次选择不同的语言,会将选择的语言存入cookie,下一次进入取cookie里面的语言,核心i18n代码在 jQuery.i18n.properties({…})这里面就是给页面需要国际化的地方赋值。

第四步:
新建不用语言的资源文件index.properties,common.properties
zh-CN/index.properties

title=i18n资源国际化

lan=语言选择:
hellomsg1=首页消息:
hellomsg2=资源国际化!这是首页消息!
searchPlaceholder=请输入搜索信息
-CN/common.properties

commonmsg1=通用消息:
commonmsg2=资源国际化!这是通用消息哦!
1
2
zh-TW/index.properties

title=i18n資源國際化

lan=語言選擇:
hellomsg1=首頁消息:
hellomsg2=資源國際化! 这是首頁消息!
searchPlaceholder=請輸入搜索信息

zh-TW/common.properties

commonmsg1=通用消息:
commonmsg2=資源國際化!這是通用消息哦!

en/index.properties

title=i18n Resource Internationalization

lan=Language:
hellomsg1=Index message:
hellomsg2=Hello word! This is index message!
searchPlaceholder=Please input serach information

en/common.properties

commonmsg1=Common message:
commonmsg2=This is common message!

注意:这里我没有按照jquery.i18n.properties上边那种strings.properties,strings_zh.properties写法写,我觉得把资源文件按语言类型文件夹划分,更直观些,故而将所有中文简体放在zh-CN下边,所有中文繁体放在zh-TW下边,英语放在en下边。会导致它每次都会去请求index_zh.properties,出现404请求错误,不过没啥大影响啦!

大功告成!

 
举报收藏 0打赏 0评论 0
 
更多>同类知识常识
推荐图文
推荐知识常识
点击排行
网站首页  |  关于我们  |  支付方式  |  联系我们  |  隐私政策  |  法律声明  |  使用协议  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报  |  企业大数据 :鲁ICP备16014150号-8