H5项目实现国际化 —— jquery.i18n.properties 解决方案demo

最近,新的VUE项目还没有开发完成,原来的老项目又提出了新的需求:国际化 (多语言切换)。在实现的过程中,有很多值得注意和分享的东西,在此写一个demo,希望对大家有帮助!

实现效果 !

 

demo 目录结构

 一, 创建html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title class="i18n" name='title'></title>
    <meta id="i18n_pagename" content="index-common">
    <title>i18n</title>
</head>
<body>
    <select id="language">
        <option value="zh-CN">中文简体</option>
        <option value="en">English</option>
    </select>
    <div>
        <h5 class="i18n" name="signOut"></h5>
        <h5 class="i18n" name="searchPlaceholder"></h5>
        <h5 class="i18n" name="station"></h5>
        <h5 class="i18n" name="partno"></h5>
        <h5 class="i18n" name="partno"></h5>
        <h5 class="i18n" name="description"></h5>
        <h5 class="i18n" name="query"></h5>
        <h5 class="i18n" name="pleaseSelect"></h>
        <h5 class="i18n" name="add"></h5>
        <h5 class="i18n" name="edit"></h5>
        <h5 class="i18n" name="delete"></h5>
    </div>
</body>
</html>
<script src="js/jquery.js"></script>
<script src="js/jquery.i18n.properties-min-1.0.9.js"></script>
<script src="js/language.extensions.js"></script>
<style>
h{
    color: red;
    font-size:20px;
}
</style>

二, 创建i18n目录

在i18n目录下的en和zh-CN各创建一个 common.properties文件 (i18n/en/common.properties      i18n/zh-CN/common.properties)

 三,  i18n/en/common.properties

searchPlaceholder=Please input serach information
signOut=Login Out

station=Station
partno=Part No
description=Description
query=Query

pleaseSelect=Please Select

add=Add
edit=Edit
delete=Delete

 四, i18n/zh-CN/common.properties

searchPlaceholder=请输入关键字
signOut=退出

station=站点
partno=零件号
description=描述
query=查询

pleaseSelect=请选择

add=新增
edit=编辑
delete=删除

 五, 在js文件创建  language.extensions.js

/**
 * cookie操作
 */
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;
    }
};

/**
 * 获取浏览器语言类型
 * @return {string} 浏览器国家语言
 */
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'];

/**
 * 执行页面i18n方法
 * @return
 */ 
var execI18n = function(){
    /*
    获取一下资源文件名
     */
    var optionEle = $("#i18n_pagename");
    if (optionEle.length < 1) {
        console.log("未找到页面名称元素,请在页面写入\n <meta id=\"i18n_pagename\" content=\"页面名(对应语言包的语言文件名)\">");
        return false;
    };
    var sourceName = optionEle.attr('content');
    sourceName = sourceName.split('-');
        /*
        首先获取用户浏览器设备之前选择过的语言类型
         */
        if (getCookie("userLanguage")) {
            i18nLanguage = getCookie("userLanguage");
        } else {
            // 获取浏览器语言
            var navLanguage = getNavLanguage();
            if (navLanguage) {
                // 判断是否在网站支持语言数组里
                var charSize = $.inArray(navLanguage, webLanguage);
                if (charSize > -1) {
                    i18nLanguage = navLanguage;
                    // 存到缓存中
                    getCookie("userLanguage",navLanguage);
                };
            } else{
                console.log("not navigator");
                return false;
            }
        }
        /* 需要引入 i18n 文件*/
        if ($.i18n == undefined) {
            console.log("请引入i18n js 文件")
            return false;
        };

        /*
        这里需要进行i18n的翻译
         */
        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("写入完毕");
            }
        });
}

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

    /*执行I18n翻译*/
    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();
    });
});

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

做到这里 貌似大功告成!当你直接在google浏览器里面运行的时候你会发现一个跨域的问题。 

 要求你在一种webServer里面去访问.properties文件,这个问题你只需要使用任何一种webserver运行即可,Apache、Node的web服务器等。

猜你喜欢

转载自www.cnblogs.com/tangwei89/p/11732928.html