网站为了国际化的需要,会使用到语言包,案例如下图。

这次尝试用js来打语言包,用到了插件 jquery.i18n.properties ,很明显,使用这个插件需要先加载jquery。

代码布局结构

 

代码下载
那就来看一下具体代码吧:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<title>js 语言包测试</title>
<style>
.zh .zh_png{
display:block;
}
.zh .en_png{
display:none;
}
.en .zh_png{
display:none;
}
.en .en_png{
display:block;
} .img_bg{
background-position:0 0;
width:30px;
height:30px;
}
.zh .img_bg{
background-image:url('img/img_bg_zh.png');
}
.en .img_bg{
background-image:url('img/img_bg_en.png');
}
</style>
</head> <body class="zh">
<div class="wrap">
<h1 data-lang="string_lang1">标题</h1>
<p data-lang="string_lang2">段落内容,balabala</p>
<ul class="nav">
<li><a data-lang="string_lang3">导航1</a></li>
<li><a data-lang="string_lang4">导航2</a></li>
<li><a data-lang="string_lang5">导航3</a></li>
<li><a data-lang="string_lang6">导航4</a></li>
</ul>
<img class="zh_png" src="img/img1_zh.png" />
<img class="en_png" src="img/img1_en.png" />
<div class="screen1">
<div class="inner">
<h1 data-lang="string_lang7">第一屏</h1>
<p data-lang="string_lang8">第一屏内容</p>
</div>
</div>
<div class="img_bg"></div>
</div>
<a id="J_lang_switch" data-lang="string_lang9">切换到英文</a>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script src="js/jquery.i18n.properties-1.0.9.js"></script>
<script>
var language_pack = {
now_lang : 0, // 0:ch,1:en
loadProperties : function(new_lang){
var self = this;
var tmp_lang = '';
if(new_lang == 0){
tmp_lang = 'zh';
$('body').removeClass('en').addClass('zh');
}else{
tmp_lang = 'en';
$('body').removeClass('zh').addClass('en');
}
jQuery.i18n.properties({//加载资浏览器语言对应的资源文件
name: 'strings', //资源文件名称
path:'language/', //资源文件路径
language: tmp_lang,
cache: false,
mode:'map', //用Map的方式使用资源文件中的值
callback: function() {//加载成功后设置显示内容
for(var i in $.i18n.map){
$('[data-lang="'+i+'"]').text($.i18n.map[i]);
}
document.title = $.i18n.map['string_title'];
}
});
self.now_lang = new_lang;
}
}
$(document).ready(function(){
language_pack.loadProperties(0); $('#J_lang_switch').click(function(){
var new_lang;
if(language_pack.now_lang == 0){
new_lang = 1;
}else{
new_lang = 0;
}
language_pack.loadProperties(new_lang);
});
});
</script>
</body>
</html>

中文语言包 strings_zh.properties

string_title=js 语言包测试
string_lang1=标题
string_lang2=段落内容,balabala
string_lang3=导航1
string_lang4=导航2
string_lang5=导航3
string_lang6=导航4
string_lang7=第一屏
string_lang8=第一屏内容
string_lang9=切换到英文

英文语言包 strings_en.properties

string_title=js language test
string_lang1=title
string_lang2=content,balabala
string_lang3=nav1
string_lang4=nav2
string_lang5=nav3
string_lang6=nav4
string_lang7=screen1
string_lang8=screen content
string_lang9=change to Chinese
/******************************************************************************
* jquery.i18n.properties
*
* Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
* MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
*
* @version 1.0.x
* @author Nuno Fernandes
* @url www.codingwithcoffee.com
* @inspiration Localisation assistance for jQuery (http://keith-wood.name/localisation.html)
* by Keith Wood (kbwood{at}iinet.com.au) June 2007
*
*****************************************************************************/ (function($) {
$.i18n = {}; /** Map holding bundle keys (if mode: 'map') */
$.i18n.map = {}; /**
* Load and parse message bundle files (.properties),
* making bundles keys available as javascript variables.
*
* i18n files are named <name>.js, or <name>_<language>.js or <name>_<language>_<country>.js
* Where:
* The <language> argument is a valid ISO Language Code. These codes are the lower-case,
* two-letter codes as defined by ISO-639. You can find a full list of these codes at a
* number of sites, such as: http://www.loc.gov/standards/iso639-2/englangn.html
* The <country> argument is a valid ISO Country Code. These codes are the upper-case,
* two-letter codes as defined by ISO-3166. You can find a full list of these codes at a
* number of sites, such as: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html
*
* Sample usage for a bundles/Messages.properties bundle:
* $.i18n.properties({
* name: 'Messages',
* language: 'en_US',
* path: 'bundles'
* });
* @param name (string/string[], optional) names of file to load (eg, 'Messages' or ['Msg1','Msg2']). Defaults to "Messages"
* @param language (string, optional) language/country code (eg, 'en', 'en_US', 'pt_PT'). if not specified, language reported by the browser will be used instead.
* @param path (string, optional) path of directory that contains file to load
* @param mode (string, optional) whether bundles keys are available as JavaScript variables/functions or as a map (eg, 'vars' or 'map')
* @param cache (boolean, optional) whether bundles should be cached by the browser, or forcibly reloaded on each page load. Defaults to false (i.e. forcibly reloaded)
* @param encoding (string, optional) the encoding to request for bundles. Property file resource bundles are specified to be in ISO-8859-1 format. Defaults to UTF-8 for backward compatibility.
* @param callback (function, optional) callback function to be called after script is terminated
*/
$.i18n.properties = function(settings) {
// set up settings
var defaults = {
name: 'Messages',
language: '',
path: '',
mode: 'vars',
cache: false,
encoding: 'UTF-8',
callback: null
};
settings = $.extend(defaults, settings);
if(settings.language === null || settings.language == '') {
settings.language = $.i18n.browserLang();
}
if(settings.language === null) {settings.language='';} // load and parse bundle files
var files = getFiles(settings.name);
for(i=0; i<files.length; i++) {
// 1. load base (eg, Messages.properties)
// 此行为博主注释
// loadAndParseFile(settings.path + files[i] + '.properties', settings);
// 2. with language code (eg, Messages_pt.properties)
if(settings.language.length >= 2) {
loadAndParseFile(settings.path + files[i] + '_' + settings.language.substring(0, 2) +'.properties', settings);
}
// 3. with language code and country code (eg, Messages_pt_PT.properties)
if(settings.language.length >= 5) {
loadAndParseFile(settings.path + files[i] + '_' + settings.language.substring(0, 5) +'.properties', settings);
}
} // call callback
if(settings.callback){ settings.callback(); }
}; /**
* When configured with mode: 'map', allows access to bundle values by specifying its key.
* Eg, jQuery.i18n.prop('com.company.bundles.menu_add')
*/
$.i18n.prop = function(key /* Add parameters as function arguments as necessary */) {
var value = $.i18n.map[key];
if (value == null)
return '[' + key + ']'; // if(arguments.length < 2) // No arguments.
// //if(key == 'spv.lbl.modified') {alert(value);}
// return value; // if (!$.isArray(placeHolderValues)) {
// // If placeHolderValues is not an array, make it into one.
// placeHolderValues = [placeHolderValues];
// for (var i=2; i<arguments.length; i++)
// placeHolderValues.push(arguments[i]);
// } // Place holder replacement
/**
* Tested with:
* test.t1=asdf ''{0}''
* test.t2=asdf '{0}' '{1}'{1}'zxcv
* test.t3=This is \"a quote" 'a''{0}''s'd{fgh{ij'
* test.t4="'''{'0}''" {0}{a}
* test.t5="'''{0}'''" {1}
* test.t6=a {1} b {0} c
* test.t7=a 'quoted \\ s\ttringy' \t\t x
*
* Produces:
* test.t1, p1 ==> asdf 'p1'
* test.t2, p1 ==> asdf {0} {1}{1}zxcv
* test.t3, p1 ==> This is "a quote" a'{0}'sd{fgh{ij
* test.t4, p1 ==> "'{0}'" p1{a}
* test.t5, p1 ==> "'{0}'" {1}
* test.t6, p1 ==> a {1} b p1 c
* test.t6, p1, p2 ==> a p2 b p1 c
* test.t6, p1, p2, p3 ==> a p2 b p1 c
* test.t7 ==> a quoted \ s tringy x
*/ var i;
if (typeof(value) == 'string') {
// Handle escape characters. Done separately from the tokenizing loop below because escape characters are
// active in quoted strings.
i = 0;
while ((i = value.indexOf('\\', i)) != -1) {
if (value[i+1] == 't')
value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab
else if (value[i+1] == 'r')
value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return
else if (value[i+1] == 'n')
value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed
else if (value[i+1] == 'f')
value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed
else if (value[i+1] == '\\')
value = value.substring(0, i) + '\\' + value.substring((i++) + 2); // \
else
value = value.substring(0, i) + value.substring(i+1); // Quietly drop the character
} // Lazily convert the string to a list of tokens.
var arr = [], j, index;
i = 0;
while (i < value.length) {
if (value[i] == '\'') {
// Handle quotes
if (i == value.length-1)
value = value.substring(0, i); // Silently drop the trailing quote
else if (value[i+1] == '\'')
value = value.substring(0, i) + value.substring(++i); // Escaped quote
else {
// Quoted string
j = i + 2;
while ((j = value.indexOf('\'', j)) != -1) {
if (j == value.length-1 || value[j+1] != '\'') {
// Found start and end quotes. Remove them
value = value.substring(0,i) + value.substring(i+1, j) + value.substring(j+1);
i = j - 1;
break;
}
else {
// Found a double quote, reduce to a single quote.
value = value.substring(0,j) + value.substring(++j);
}
} if (j == -1) {
// There is no end quote. Drop the start quote
value = value.substring(0,i) + value.substring(i+1);
}
}
}
else if (value[i] == '{') {
// Beginning of an unquoted place holder.
j = value.indexOf('}', i+1);
if (j == -1)
i++; // No end. Process the rest of the line. Java would throw an exception
else {
// Add 1 to the index so that it aligns with the function arguments.
index = parseInt(value.substring(i+1, j));
if (!isNaN(index) && index >= 0) {
// Put the line thus far (if it isn't empty) into the array
var s = value.substring(0, i);
if (s != "")
arr.push(s);
// Put the parameter reference into the array
arr.push(index);
// Start the processing over again starting from the rest of the line.
i = 0;
value = value.substring(j+1);
}
else
i = j + 1; // Invalid parameter. Leave as is.
}
}
else
i++;
} // Put the remainder of the no-empty line into the array.
if (value != "")
arr.push(value);
value = arr; // Make the array the value for the entry.
$.i18n.map[key] = arr;
} if (value.length == 0)
return "";
if (value.lengh == 1 && typeof(value[0]) == "string")
return value[0]; var s = "";
for (i=0; i<value.length; i++) {
if (typeof(value[i]) == "string")
s += value[i];
// Must be a number
else if (value[i] + 1 < arguments.length)
s += arguments[value[i] + 1];
else
s += "{"+ value[i] +"}";
} return s;
}; /** Language reported by browser, normalized code */
$.i18n.browserLang = function() {
return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
} /** Load and parse .properties files */
function loadAndParseFile(filename, settings) {
$.ajax({
url: filename,
async: false,
cache: settings.cache,
contentType:'text/plain;charset='+ settings.encoding,
dataType: 'text',
success: function(data, status) {
parseData(data, settings.mode);
}
});
} /** Parse .properties files */
function parseData(data, mode) {
var parsed = '';
var parameters = data.split( /\n/ );
var regPlaceHolder = /(\{\d+\})/g;
var regRepPlaceHolder = /\{(\d+)\}/g;
var unicodeRE = /(\\u.{4})/ig;
for(var i=0; i<parameters.length; i++ ) {
parameters[i] = parameters[i].replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
if(parameters[i].length > 0 && parameters[i].match("^#")!="#") { // skip comments
var pair = parameters[i].split('=');
if(pair.length > 0) {
/** Process key & value */
var name = unescape(pair[0]).replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim
var value = pair.length == 1 ? "" : pair[1];
// process multi-line values
while(value.match(/\\$/)=="\\") {
value = value.substring(0, value.length - 1);
value += parameters[++i].replace( /\s\s*$/, '' ); // right trim
}
// Put values with embedded '='s back together
for(var s=2;s<pair.length;s++){ value +='=' + pair[s]; }
value = value.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' ); // trim /** Mode: bundle keys in a map */
if(mode == 'map' || mode == 'both') {
// handle unicode chars possibly left out
var unicodeMatches = value.match(unicodeRE);
if(unicodeMatches) {
for(var u=0; u<unicodeMatches.length; u++) {
value = value.replace( unicodeMatches[u], unescapeUnicode(unicodeMatches[u]));
}
}
// add to map
$.i18n.map[name] = value;
} /** Mode: bundle keys as vars/functions */
if(mode == 'vars' || mode == 'both') {
value = value.replace( /"/g, '\\"' ); // escape quotation mark (") // make sure namespaced key exists (eg, 'some.key')
checkKeyNamespace(name); // value with variable substitutions
if(regPlaceHolder.test(value)) {
var parts = value.split(regPlaceHolder);
// process function args
var first = true;
var fnArgs = '';
var usedArgs = [];
for(var p=0; p<parts.length; p++) {
if(regPlaceHolder.test(parts[p]) && (usedArgs.length == 0 || usedArgs.indexOf(parts[p]) == -1)) {
if(!first) {fnArgs += ',';}
fnArgs += parts[p].replace(regRepPlaceHolder, 'v$1');
usedArgs.push(parts[p]);
first = false;
}
}
parsed += name + '=function(' + fnArgs + '){';
// process function body
var fnExpr = '"' + value.replace(regRepPlaceHolder, '"+v$1+"') + '"';
parsed += 'return ' + fnExpr + ';' + '};'; // simple value
}else{
parsed += name+'="'+value+'";';
}
} // END: Mode: bundle keys as vars/functions
} // END: if(pair.length > 0)
} // END: skip comments
}
eval(parsed);
} /** Make sure namespace exists (for keys with dots in name) */
// TODO key parts that start with numbers quietly fail. i.e. month.short.1=Jan
function checkKeyNamespace(key) {
var regDot = /\./;
if(regDot.test(key)) {
var fullname = '';
var names = key.split( /\./ );
for(var i=0; i<names.length; i++) {
if(i>0) {fullname += '.';}
fullname += names[i];
if(eval('typeof '+fullname+' == "undefined"')) {
eval(fullname + '={};');
}
}
}
} /** Make sure filename is an array */
function getFiles(names) {
return (names && names.constructor == Array) ? names : [names];
} /** Ensure language code is in the format aa_AA. */
function normaliseLanguageCode(lang) {
lang = lang.toLowerCase();
if(lang.length > 3) {
lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
}
return lang;
} /** Unescape unicode chars ('\u00e3') */
function unescapeUnicode(str) {
// unescape unicode codes
var codes = [];
var code = parseInt(str.substr(2), 16);
if (code >= 0 && code < Math.pow(2, 16)) {
codes.push(code);
}
// convert codes to text
var unescaped = '';
for (var i = 0; i < codes.length; ++i) {
unescaped += String.fromCharCode(codes[i]);
}
return unescaped;
} /* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function(str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
if(typeof cbSplit._nativeSplit == "undefined")
return str.split(separator, limit);
else
return cbSplit._nativeSplit.call(str, separator, limit);
} var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength; str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
} /* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
} while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index)); // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
} if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
} lastLength = match[0].length;
lastLastIndex = lastIndex; if (output.length >= limit) {
break;
}
} if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
} if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
} return output.length > limit ? output.slice(0, limit) : output;
}; cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split; } // end `if (!cbSplit)`
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
}; })(jQuery);

jquery.i18n.properties-1.0.9.js

原文:https://www.jianshu.com/p/8b4c63e1cf25

demo:https://codepen.io/AndreCortellini/pen/xPMEWK

jquery.i18n.properties的使用讲解与实例:https://blog.csdn.net/m0_37566424/article/details/79070218

js多语言切换demo的更多相关文章

  1. ASP.NET MVC5多语言切换快速实现方案

    功能 实现动态切换语言,Demo做了三种语言库可以切换,包括资源文件的定义,实体对象属性设置,后台代码Controller,IAuthorizationFilter,HtmlHelper的实现,做法比 ...

  2. vue-i18n 国际化语言切换

    vue-i18n 用于前端vue项目中,需要多语言切换的场景 安装方法(npm) npm install vue-i18n 简单使用   1.在vue项目的main.ts文件中实例化 i18n imp ...

  3. react项目实现多语言切换

    网站的语言切换功能大家都见过不少,一般都是一个下拉框选择语言,如果让我们想一下怎么实现这个功能,我相信大家都是有哥大概思路,一个语言切换的select,将当前的选择的语言存在全局,根据这个语言的key ...

  4. bootstrap table 插件多语言切换

    在bootstrap中的bootstrap table 插件在多语言切换的审核,只需要如下操作 引入bootstrap-table-locale-all.js文件 $('#Grid').bootstr ...

  5. 如何实现Echart不刷新页面,多语言切换下的地图数据重新加载,api请求数据加载,soketed数据实时加载

    可视化项目中经常用到ecahrt,各种异步加载,连接socket,多语言切换等问题,现在汇总一下: Ecahrt初始化,全局统一init,可以初始化为0,等待后续数据操作 1.如果是api重新请求,数 ...

  6. vue 国际化i18n 多语言切换

    安装 npm install vue-i18n 新建一个文件夹 i18n ,内新建 en.js zh.js index.js 三个文件 准备翻译信息 en.js export default { ho ...

  7. JS图片Switchable切换大集合

    JS图片切换大集合 利用周末2天把JS图片切换常见效果封装了下,比如:轮播,显示隐藏,淡入淡出等.废话不多说,直接看效果吧!JSFiddler链接如下: 想看JS轮播切换效果请点击我! 当然由于上传图 ...

  8. vue-i18n vue-cli项目中实现国际化 多语言切换功能 一

    vue-cli项目中引入vue-i18n 安装: npm install vue-i18n可参考vue-i18n官网文档 main.js中引入: import Vue from 'vue' impor ...

  9. WPF语言切换,国际化

    winform语言切换在每个窗口下面有一个.resx结尾的资源文件,在上面添加新字符串就好了: WPF语言切换跟winform不一样的地方在于需要自己添加资源文件,并且这个资源文件可以写一个,也可以写 ...

随机推荐

  1. css 添加一个图标始终保持在pc端的右下角

    <div class="dialog_maxdiv" style="display:block;"> <div id="center ...

  2. virtualbox迁移虚拟机

    我用的Ubuntu16.04,下图为装好virtualbox时安装好系统后默认的存储位置. 促使我想迁移的原因是我的/home下因为虚拟机的存储原因导致/home下还剩1.5M可用空间..... 该目 ...

  3. Django Model模型

    Model简介 模型准确且唯一的描述了数据.它包含您储存的数据的重要字段和行为.一般来说,每一个模型都映射一张数据库表. 每个模型都是一个 Python 的类,这些类继承 django.db.mode ...

  4. eclipse中Maven web项目的目录结构浅析

    刚开始接触maven web项目的时候,相信很多人都会被它的目录结构迷惑. 为了避免初学者遇到像我一样的困扰,我就从一个纯初学者的视角,来分析一下这个东西. 1,比如说,我们拿一个常见的目录结构来看, ...

  5. 概率dp作业

    概率dp特征: 概率DP一般求的是实际结果,在DP过程中,当前状态是由所有子状态的概率共同转移而来,所以概率DP只是利用了DP的动态而没有规划(即只需转移无需决策).-------qkoqhh A - ...

  6. iptable和tcpdump的先后顺序

    tcpdump是一个用来抓取linux网络数据包的工具,而iptables是linux上的防火墙工具,两者之间的顺序是: Wire -> NIC -> tcpdump -> netf ...

  7. Python multiprocess模块(中)

    主要内容: 一. 锁 二. 信号量 三. 事件 通过event来完成红绿灯模型 四. 队列(重点) 队列实现进程间的通信 五. 生产者消费者模型 1. 初始版本(程序会阻塞住) 2. 升级版本一(通过 ...

  8. Angular ViewChild & ViewChildren

    基础 ViewChild ViewChild 装饰器用于获取模板视图中的元素或直接调用其组件中的方法.它支持 Type 类型或 string 类型的选择器,同时支持设置 read 查询条件,以获取不同 ...

  9. #内存不够,swap来凑# Linux上创建SWAP文件/分区

    转自:https://www.vmvps.com/how-to-create-a-swap-file-on-the-linux-os.html 很久很久以前,电脑的内存是个珍贵东西,于是乎就有了swa ...

  10. idea连接docker实现一键部署

    一.修改配置文件,打开2375端口 [root@microservice ~]# vim /usr/lib/systemd/system/docker.service 在ExecStart=/usr/ ...