目的:在纯js、jq的项目中引入i18n 。实现网站的多语言切换。
一、项目结构
js文件夹:在项目中引入jQuery,因为是基于JQuery的。引入jQuery版本的i18n,后面有下载地址。
lang文件夹:里面存放自定义的语言包。
index.html : 案例demo
![](https://img.haomeiwen.com/i14938235/865b57806365f5ed.png)
二、下载 i18n
下面是github地址,克隆下来,会得到一个文件夹。
https://github.com/jquery-i18n-properties/jquery-i18n-properties
![](https://img.haomeiwen.com/i14938235/16f07df0fe8eceff.png)
我们这里只需要把 jquery.i18n.properties.js 文件拷贝到我们的项目中即可。
三、新建语言包 - lang文件夹
1、文件夹名是自己取的名字(lang),随便取什么都行,但是后面引入时,要一致。
2、在文件夹下面手动新建你所需要的语言包,我这边是中文和英文。(注意:文件名要规范,文件名_国家代号.properties。例如:strings_en.properties)
![](https://img.haomeiwen.com/i14938235/9f37c8b56541231b.png)
![](https://img.haomeiwen.com/i14938235/037f8569e74f3602.png)
四、html代码
<html lang="en">
<head>
<meta charset="UTF-8">
<title>国际化</title>
<script src="./js/jquery-3.4.1.js"></script>
<script src="./js/jquery.i18n.properties.js"></script>
</head>
<body>
<button id='btn' data-locale="BtnChange">切换语言</button>
<div>
<p data-locale="Login">登录</p>
<p data-locale="UserName">用户名:</p>
<p data-locale="Password">密码:</p>
</div>
<script type="text/javascript">
isEng = true
btn.onclick = function () {
if (!isEng) {
loadProperties('en');
} else {
loadProperties('zh');
}
isEng = !isEng
}
function loadProperties(lang) {
$.i18n.properties({
name: 'strings', //资源文件名称 , 命名格式: 文件名_国家代号.properties
path: 'lang/', //资源文件路径,注意这里路径是你属性文件的所在文件夹,可以自定义。
mode: 'map', //用 Map 的方式使用资源文件中的值
language: lang, //这就是国家代号 name+language刚好组成属性文件名:strings+zh -> strings_zh.properties
callback: function () {
$("[data-locale]").each(function () {
console.log($(this).data("locale"));
$(this).html($.i18n.prop($(this).data("locale")));
});
}
});
}
loadProperties('en');//调用
</script>
</body>
</html>
代码说明:
1、切换语言按钮点击时,isEng取反,这样可以实现一个按钮两个种功能。
2、loadProperties()方法要调用。如果你想默认中文的话就传值 “zh” 即可。
3、name:传值(strings_en.properties)中的 strings。
4、path:传值 lang文件夹名,注意要加 / 。
5、language:获取到的就是(strings_en.properties)中的 en。
6、callback : 就是遍历data-locale 中的值,给对应的键名添加内容。
以上就是全部代码。这样就可以实现,点击按钮切换不同的语言。
网友评论