console.log(字典)会给您
{“ click here:”:{“ message”:“点击这里”},“ apply”:{“ message”:“应用”},“翻译测试!”:{“ message”:“ js翻译示例!“},” tabLanding“:”欢迎“,” tabSetup“:{” message“:”安装“}}
我希望tabSetup看起来像在html中安装 这是html代码:
<li class="tab_setup"><a href="#" i18n="tabSetup"></a></li>
我看到的是它不能正确显示,只是显示为[object Object] 它应该显示为安装
这是我的Java脚本。谢谢
var dict = {};
var systemLang = navigator.language.toLowerCase().slice(0,2);
$(function () {
registerWords();
switch(getCookieVal("lang")) {
case "en" :
setLanguage("en");
break
case "zh" :
setLanguage("zh");
break
default:
setLanguage(systemLang);
}
console.log (dict);
console.log(JSON.stringify(dict));
// 切换语言事件
$("#enBtn").bind("click", function () {
setLanguage("en");
});
$("#zhBtn").bind("click", function () {
setLanguage("zh");
});
// $("#applyBtn").bind("click", function () {
// alert(__tr("a translation test!"));
// });
});
function setLanguage(lang) {
setCookie("lang=" + lang + "; path=/;");
translate(lang);
}
function getCookieVal(name) {
var items = document.cookie.split(";");
for (var i in items) {
var cookie = $.trim(items[i]);
var eqIdx = cookie.indexOf("=");
var key = cookie.substring(0, eqIdx);
if (name == $.trim(key)) {
return $.trim(cookie.substring(eqIdx + 1));
}
}
return null;
}
function setCookie(cookie) {
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = cookie+ ";expires=" + exp.toGMTString();
}
function translate(lang) {
if(sessionStorage.getItem(lang + "Data") != null){
dict = JSON.parse(sessionStorage.getItem(lang + "Data"));
}else{
loadDict();
}
$("[i18n]").each(function () {
switch (this.tagName.toLowerCase()) {
case "input":
$(this).val(__tr($(this).attr("i18n")));
break;
default:
$(this).text(__tr($(this).attr("i18n")));
}
});
}
function __tr(src) {
return (dict[src] || src);
}
function loadDict() {
var lang = (getCookieVal("lang") || "en");
$.ajax({
async: false,
type: "GET",
url: "/lang/"+lang + ".json",
success: function (msg) {
dict = msg;
sessionStorage.setItem(lang + 'Data', JSON.stringify(dict));
}
});
}
// 遍历所有lang属性的标签赋值
function registerWords() {
$('[i18n]:not(.i18n-replaced').each(function() {
var element = $(this);
element.html(translate(element.attr('i18n')));
element.addClass('i18n-replaced');
});
}
如果json文件(例如“ tabSetup”:“ Set up”)有效。 。如果json文件(例如“ tabSetup”:{“ message”:“ Set up”}
答案 0 :(得分:1)
函数__tr出现错误,像这样修复
function __tr(src) {
return (dict[src].message || src);
}