若是新项目要作系统国际化, 时下热门的任何一种技术选型都有成熟的方案,好比:html
可是老项目的国际化几乎是jquery + jquery.i18n.properties这种方案. 那么咱们就来看看这种方案是如何实现的.vue
在项目中添加以下目录结构:react
<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-placeholder
、data-i18n-text
、data-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