利用jquery.i18n.properties实现前端网页国际化小示例(详细版)

您所在的位置:网站首页 jquery切换语言 利用jquery.i18n.properties实现前端网页国际化小示例(详细版)

利用jquery.i18n.properties实现前端网页国际化小示例(详细版)

2024-07-10 15:12| 来源: 网络整理| 查看: 265

利用jquery.i18n.properties实现前端网页国际化小示例(详细版)

文件目录结构: 在这里插入图片描述

index.html

DOCTYPE html> jQuery.i18n.properties Example $(document).ready(function () { // 加载属性文件 jQuery.i18n.properties({ name: 'messages', //属性文件名 path: 'i18n/', //属性文件路径 mode: 'map', //用map来存储属性值 language: 'zh', //默认语言 callback: function () { // 设置页面上的文本 $('body').find('*').each(function () { if ($(this).attr('data-i18n')) { $(this).html($.i18n.prop($(this).attr('data-i18n'))); } }); // $('body').i18n(); } }); // 切换语言 $('#langSelect').change(function () { var lang = $(this).val(); jQuery.i18n.properties({ name: 'messages', path: 'i18n/', mode: 'map', language: lang, callback: function () { $('body').find('*').each(function () { if ($(this).attr('data-i18n')) { $(this).html($.i18n.prop($(this).attr('data-i18n'))); } }); } }); }); }); 中文 English 我是标题 我是标题描述

jquery.i18n.properties.js

访问jQuery.i18n.properties插件的官方GitHub仓库也可以自行下载:https://github.com/jquery-i18n-properties/jquery-i18n-properties

/****************************************************************************** * 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.2.7 * @url https://github.com/jquery-i18n-properties/jquery-i18n-properties * @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 is 'map' or 'both'. Values of this can also be an * Object, in which case the key is a namespace. */ $.i18n.map = {}; var debug = function (message) { window.console && console.log('i18n::' + message); }; /** * Load and parse message bundle files (.properties), * making bundles keys available as javascript variables. * * i18n files are named .js, or _.js or __.js * Where: * The 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 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_BR'). 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 debug (boolean, optional) whether debug statements are logged at the console * @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) { var defaults = { name: 'Messages', language: '', path: '', namespace: null, mode: 'vars', cache: false, debug: false, encoding: 'UTF-8', async: false, callback: null }; settings = $.extend(defaults, settings); if (settings.namespace && typeof settings.namespace == 'string') { // A namespace has been supplied, initialise it. if (settings.namespace.match(/^[a-z]*$/)) { $.i18n.map[settings.namespace] = {}; } else { debug('Namespaces can only be lower case letters, a - z'); settings.namespace = null; } } // Ensure a trailing slash on the path if (!settings.path.match(/\/$/)) settings.path += '/'; // Try to ensure that we have at a least a two letter language code settings.language = this.normaliseLanguageCode(settings); // Ensure an array var files = (settings.name && settings.name.constructor === Array) ? settings.name : [settings.name]; // A locale is at least a language code which means at least two files per name. If // we also have a country code, thats an extra file per name. settings.totalFiles = (files.length * 2) + ((settings.language.length >= 5) ? files.length : 0); if (settings.debug) { debug('totalFiles: ' + settings.totalFiles); } settings.filesLoaded = 0; files.forEach(function (file) { var defaultFileName, shortFileName, longFileName, fileNames; // 1. load base (eg, Messages.properties) defaultFileName = settings.path + file + '.properties'; // 2. with language code (eg, Messages_pt.properties) var shortCode = settings.language.substring(0, 2); shortFileName = settings.path + file + '_' + shortCode + '.properties'; // 3. with language code and country code (eg, Messages_pt_BR.properties) if (settings.language.length >= 5) { var longCode = settings.language.substring(0, 5); longFileName = settings.path + file + '_' + longCode + '.properties'; fileNames = [defaultFileName, shortFileName, longFileName]; } else { fileNames = [defaultFileName, shortFileName]; } loadAndParseFiles(fileNames, settings); }); // call callback if (settings.callback && !settings.async) { settings.callback(); } }; // properties /** * 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 args = [].slice.call(arguments); var phvList, namespace; if (args.length == 2) { if ($.isArray(args[1])) { // An array was passed as the second parameter, so assume it is the list of place holder values. phvList = args[1]; } else if (typeof args[1] === 'object') { // Second argument is an options object {namespace: 'mynamespace', replacements: ['egg', 'nog']} namespace = args[1].namespace; var replacements = args[1].replacements; args.splice(-1, 1); if (replacements) { Array.prototype.push.apply(args, replacements); } } } var value = (namespace) ? $.i18n.map[namespace][key] : $.i18n.map[key]; if (value === null) { return '[' + ((namespace) ? namespace + '#' + key : key) + ']'; } // 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.charAt(i + 1) == 't') { value = value.substring(0, i) + '\t' + value.substring((i++) + 2); // tab } else if (value.charAt(i + 1) == 'r') { value = value.substring(0, i) + '\r' + value.substring((i++) + 2); // return } else if (value.charAt(i + 1) == 'n') { value = value.substring(0, i) + '\n' + value.substring((i++) + 2); // line feed } else if (value.charAt(i + 1) == 'f') { value = value.substring(0, i) + '\f' + value.substring((i++) + 2); // form feed } else if (value.charAt(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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3