1.項目文件及目錄
2.準備js
github下載地址:https://github.com/T-baby/jquery.i18n/releases
3.頁面代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>i18n-json數據切換中英文</title>
</head>
<body>
<span i18n="login.username">賬號:</span><input type="text" name="" i18n="login.enter_user" placeholder="請輸入賬號">
<br />
<span i18n="login.password">密碼:</span><input type="password" name="" i18n="login.enter_pass" placeholder="請輸入密碼">
<br />
<select id="changeLanguage">
<option i18n="login.choice_langu">請選擇語言</option>
<option i18n="login.ch">中文</option>
<option i18n="login.en">英語</option>
</select>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.i18n.min.js"></script>
<script type="text/javascript">
$(function(){
defaultLanguage();
})
var langStr="cn";
function defaultLanguage(){
// alert(langStr);
$("[i18n]").i18n({
defaultLang: langStr,
filePath: "./i18n/",
filePrefix: "i18n_",
fileSuffix: "",
forever: true,
callback: function(res) {}
});
}
$('#changeLanguage').change(function(){
var language=$('#changeLanguage option:selected').val();
if(language=="英語" || language=="English"){
langStr="en";
}else{
langStr="cn";
}
defaultLanguage();
});
</script>
</body>
</html>
4.json數據
中文:i18n_cn.json
{
"login.username":"賬號:",
"login.password":"密碼:",
"login.enter_user":"請輸入賬號",
"login.enter_pass":"請輸入密碼",
"login.choice_langu":"請選擇語言",
"login.ch":"中文",
"login.en":"英語"
}
英文數據:i18n_en.json
{
"login.username":"username:",
"login.password":"password:",
"login.enter_user":"Please enter your username",
"login.enter_pass":"Please enter your password",
"login.choice_langu":"Please select a language",
"login.ch":"Chinese",
"login.en":"English"
}
5.注意事項
a.如果只是靜態文件會報如下錯誤,告訴我們訪問數據時需要加載服務器資源,純靜態頁面建議使用Hbuilder web服務器方式運行
~~~~直接訪問file:///D:/Users/Administrator/Desktop/i18nDemo/index.html文件報錯
jquery.js:4 Access to XMLHttpRequest at 'file:///D:/Users/Administrator/Desktop/i18nDemo/i18n/i18n_cn.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
~~~~Hbuilder本地服務器方式正常:http://127.0.0.1:8020/i18nDemo/index.html?__hbt=1563420319456
b.i18n參數詳解
defaultLang
defaultLang: defaultLang,
默認語言名稱,插件會自動將 filePrefix
+defaultLang
+fileSuffix
拼接在一起作爲語言文件文件名。
filePath
filePath: "/i18n/",
該參數指定了語言文件所在文件夾在項目中的位置。
filePrefix
filePrefix: "i18n_",
該參數指定了語言文件的命名的前綴。
fileSuffix
fileSuffix: "",
該參數指定了語言文件的命名的後綴。
callback
callback:function(){
//do something
}
6.參考文章:https://juejin.im/entry/58774b70b123db005dd49e62
7.其他方案(四種方式實現前端國際化):https://blog.csdn.net/qq_41485414/article/details/81093999