jquery.i18n.properties前端国际化方案

若是新项目要作系统国际化, 时下热门的任何一种技术选型都有成熟的方案,好比:html

  1. vue + vue-i18n
  2. angular + angular-translate
  3. react + react-intl

可是老项目的国际化几乎是jquery + jquery.i18n.properties这种方案. 那么咱们就来看看这种方案是如何实现的.vue

一. 引入必要的 js 文件

在项目中添加以下目录结构:react

Exb3se.png

<script src="js/jquery.min.js"></script>
<script src="js/jquery.i18n.properties-1.0.9.js"></script>

二. 资源文件准备

i18n/resource/common.propertiesjquery

name='姓名'
placeholder='请输入电话号码'
login='登陆'

i18n/resource/common_en.propertiesthis

name='name'
placeholder= 'Please enter phone number'
login='login'

三. 标签赋值

通常状况下,咱们标签里面的内容若是要作国际化,须要使用 $('#id').text($.i18n.prop('proName')); 来给标签赋值,如今问题来了,咱们开发一个界面,有不少地方都须要去作国际化,咱们总不能这样每个页面每个标签经过这种方式去赋值吧,这样工做量不是一点大,因而乎博主想,有没有一种比较好的通用的解决方案去给这些须要作国际化的标签统一赋值呢。html的data属性彷佛是一个不错的选择!它具备可读性强、可维护性强、兼容jquery的data()方法等优势。好比咱们修改国际化组件的方法以下code

<script>
    $(function(){
        jQuery.i18n.properties({
            name : 'common', //资源文件名称
            path : '/i18n/resource/', //资源文件路径
            mode : 'map', //用Map的方式使用资源文件中的值
                callback : function() {
                     console.log("i18n赋值中...");
                        try {
                            //初始化页面元素
                            $('[data-i18n-placeholder]').each(function () {
                                $(this).attr('placeholder', $.i18n.prop($(this).data('i18n-placeholder')));
                            });
                            $('[data-i18n-text]').each(function () {
                                //若是text里面还有html须要过滤掉
                                var html = $(this).html();
                                var reg = /<(.*)>/;
                                if (reg.test(html)) {
                                    var htmlValue = reg.exec(html)[0];
                                    $(this).html(htmlValue + $.i18n.prop($(this).data('i18n-text')));
                                }
                                else {
                                    $(this).text($.i18n.prop($(this).data('i18n-text')));
                                }
                            });
                            $('[data-i18n-value]').each(function () {
                                $(this).val($.i18n.prop($(this).data('i18n-value')));
                            });
                        }
                        catch(ex){ }
                        console.log("i18n写入完毕");
                }
            });
        });
    </script>

经过data属性获取标签,而后对每一个标签经过对应的data-i18n-属性进行国际化赋值便可,这里暂时定义了三种类型data-i18n-placeholderdata-i18n-textdata-i18n-value的属性,若是有其余需求,能够增长其余类型。
而后看下咱们html页面的使用htm

<p data-i18n-text='name'></p>
<input type="text" data-i18n-placeholder="placeholder">
<input type="button" data-i18n-value="login"></input>

这样不用写一句标签的赋值代码,便可对标签进行国际化blog

四. 最终效果

  • 中文环境下:

Ex7vh6.png

  • 英文环境下:

Ex7jtx.png

相关文章
相关标签/搜索