前端那些中之 jquery.i18n 国际化

jquery.i18n 国际化

  • 第一部: jquery.i18n插件
/*!
 * jQuery i18n Plugin v1.0.0
 * https://github.com/ZOMAKE/jquery.i18n
 *
 * Copyright 2017 ZOMAKE,Inc.
 * Released under the Apache Licence 2.0
 */
(function($) {
    $.extend({
        i18nData:{},
        isLoadi18n:false,
        rootPath:undefined,
        loadDefaulti18n:function(path){
            if(path){
                $.rootPath = path;
            }
            // if(!$.rootPath){
            //     $.rootPath = '/math';
            // }
            if(!$.isLoadi18n){
                $("[i18n]").i18n({
                    filePath: "/static/i18n/", //路径名称
                    filePrefix: "i18n_",
                    fileSuffix: "",
                    forever: true,
                    callback: function() {
                        console.log("i18n is ready.");
                        isLoadi18n = true;
                    }
                });
            }

        },
        getCookie:function (name) {
            var arr = document.cookie.split('; ');
            for (var i = 0; i < arr.length; i++) {
                var arr1 = arr[i].split('=');
                if (arr1[0] == name) {
                    return arr1[1];
                }
            }
            return '';
        },
        setCookie:function(name, value, myDay){
            var oDate = new Date();
            oDate.setDate(oDate.getDate() + myDay);
            document.cookie = name + '=' + value + '; expires=' + oDate;
        },
        getIi8nText:function(key){
            if($.i18nData){
                var text = $.i18nData[key];
                if(text){
                    return text;
                }else{
                    return "";
                }
            }else{
                return "";
            }
        }
    });
    $.fn.extend({
        i18n: function(options) {
            var defaults = {
                lang: "",
                defaultLang: "",
                filePath: "/i18n/",
                filePrefix: "i18n_",
                fileSuffix: "",
                forever: true,
                callback: function() {}
            };

            var options = $.extend(defaults, options);


            if(options.defaultLang != null && options.defaultLang != ""){
                options.lang = defaults.defaultLang;
                if (options.forever) {
                    $.setCookie('i18n_lang', options.lang);
                } else {
                    $.removeCookie("i18n_lang");
                }
            }else{
                if ($.getCookie('i18n_lang') != "" && $.getCookie('i18n_lang') != "undefined" && $.getCookie('i18n_lang') != null) {
                    options.lang = $.getCookie('i18n_lang');
                } else if (options.lang == "" && defaults.defaultLang == "") {
                    options.lang='cn';
                    $.setCookie('i18n_lang', options.lang);
                };
            }

            var i = this;
            $.ajaxSettings.async = false;
            $.getJSON(options.filePath + options.filePrefix + options.lang + options.fileSuffix + ".json", function(data) {
                $.ajaxSettings.async = true;
                var i18nLang = {};
                if (data != null) {
                    i18nLang = data;
                }
                $.i18nData= i18nLang;

                $(i).each(function(i) {
                    var i18nOnly = $(this).attr("i18n-only");
                    var i18ntext = $(this).attr("i18n");
                    //console.log("to convert the key:"+i18ntext+",type="+i18nOnly);

                    if ($(this).attr(i18nOnly) != null && $(this).attr(i18nOnly) != "") {
                        $(this).attr(i18nOnly, i18nLang[i18ntext])
                    }else{
                        if ($(this).val() != null && $(this).val() != "") {
                            if (i18nOnly == null || i18nOnly == undefined || i18nOnly == "" || i18nOnly == "value") {
                                $(this).val(i18nLang[i18ntext])
                            }
                        }
                        if ($(this).html() != null && $(this).html() != "") {
                            if ((i18nOnly == null || i18nOnly == undefined || i18nOnly == "" || i18nOnly == "html")&&i18nOnly!="title") {
                                $(this).html(i18nLang[i18ntext])
                            }
                        }
                        if ($(this).attr('placeholder') != null && $(this).attr('placeholder') != "") {
                            if (i18nOnly == null || i18nOnly == undefined || i18nOnly == "" || i18nOnly == "placeholder") {
                                $(this).attr('placeholder', i18nLang[i18ntext])
                            }
                        }


                        if ($(this).attr('title') != null && $(this).attr('title') != "") {
                            $(this).attr('title', i18nLang[i18ntext])
                        }
                    }
                });
                options.callback();
            });
        }
    });
})(jQuery);

  • 第二部:static目录下放json文件

输入图片说明

  • 在json里写入要翻译的内容
  • i18n_cn.json
{

    "room.Update":"更新",
    "room.Update.room":"更新机房",
    "room.Create":"创建",
    "room.Create.room":"创建机房",
    "room.create.message":"正在创建机房。。。",
    "room.delete.message":"你确定要删除这个机房吗?",
    "room.delete.tip":"正在删除机房。。。",
    "room.name.exist":"名字已经存在"
}
  • i18n_en.json
{
    "room.Update":"Update",
    "room.Update.room":"Update Room",
    "room.Create":"Create",
    "room.Create.room":"Create Room",
    "room.create.message":"Creating The Room.",
    "room.delete.message":"Are you sure to delete this room ?",
    "room.delete.tip":"Deleting The room.",
    "room.name.exist":"name already exist"
}
  • 第三部:引入jquery.i18n插件
<script src="/static/plugins/jquery/dist/jquery.min.js"></script>
        <!--jquery i18n 翻译-->
   <script src="/static/plugins/jquery.i18n/jquery.i18n.js"></script>
  
  • 第四部:刚引入完成就加载
<script src="/static/plugins/jquery/dist/jquery.min.js"></script>
        <!--jquery i18n 翻译-->
   <script src="/static/plugins/jquery.i18n/jquery.i18n.js"></script>
  
 <script>
                $(document).ready(function() {
                    $.loadDefaulti18n();
                  
                });
  </script>
  • 第五部:在html 里调用
<span class="label-key" i18n="room.Update" i18n-only="html"> Name:</span>
  • 第六部:在js里调用
 $('#fHost .modal-title').html($.getIi8nText('room.Create.room'))

js实现语言切换配合i18n

  • html 页面
 <li id="m_language">
                <span id="curr_language" data-language="cn" class="language_a">dddddddd</span>
     </li>
  • js部分
  $(function () {
        var languageObj = {"cn": "中文", "en": "English"};

        function initLanguage() {
            var sessionIi8n = sessionStorage.getItem('i18n_lang');
            if (sessionIi8n) {
                $.setCookie('i18n_lang', sessionIi8n);
            }
            var language = $.getCookie('i18n_lang');
            if (!(language != "" && language != "undefined" && language != null)) {
                language = 'cn';
            }
            if (language == 'cn') {
                language = 'en';
            } else {
                language = 'cn';
            }
            $('#curr_language').attr("data-language", language).text(languageObj[language]);
        }

        initLanguage();

        $("#m_language").on('click', '.language_a', function () {
            var language = $(this).attr("data-language");
            $("[i18n]").i18n({
                defaultLang: language,
                filePath: "/static/i18n/"
            });
            console.log($("[i18n]").i18n());
            sessionStorage.setItem("i18n_lang", language);
            if (language == 'cn') {
                language = 'en';
                window.location.reload();
            } else {
                language = 'cn';
                window.location.reload();
            }
            $(this).attr("data-language", language).text(languageObj[language]);
        });

    });
</script>

转载于:https://my.oschina.net/yongxinke/blog/1537840

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值