我知道document.write
是邪恶的,不应该用于在网站上输出文本。
还没有找到更好的解决方案,我通过页面上的javascript输出翻译文本。考虑一下:
我的模板代码如下所示:
<h1><script>_e("title");</script></h1>
在javascript文件中,我有类似的代码来翻译strigs:
// Initialize the dictionaries and set current language.
window.lang = {};
window.lang.en = { "title": "Sample Page" };
window.lang.de = { "title": "Beispiel Seite" };
window.curLang = "en";
// Translation function that should output translated text.
function _e(text) {
var dictionary = window.lang[window.curLang];
var translation = dictionary[text];
// BELOW LINE IS EVIL.
// But what's the alternative without having to change the template code above?
document.write( translation );
}
问题:
我可以在不更改模板代码的情况下将 javascript 函数更改为不使用 document.write
工作吗?如果没有:这里翻译的最佳解决方案是什么?
这是我第一次使用 document.currentScript,但我尝试过这段代码,它应该可以正常工作:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" charset="utf-8">
// Initialize the dictionaries and set current language.
window.lang = {};
window.lang.en = { "title": "Sample Page" };
window.lang.de = { "title": "Beispiel Seite" };
window.curLang = "en";
// Translation function that should output translated text.
function _e(text) {
var dictionary = window.lang[window.curLang];
var translation = dictionary[text];
var container = document.currentScript;
container.parentNode.innerHTML = translation;
}
</script>
</head>
<body>
<h1><script>_e("title");</script></h1>
</body>
</html>
另一个原因是使用特殊标签或属性替换为jQuery之类的东西,但这会改变你的模板。类似的东西
<span class='i18n-text'>title</span>
var dictionary = window.lang[window.curLang];
jQuery('.i18n-text').each(function(){
var text = $(this).text();
var translation = dictionary[text];
$(this).html(translation);
});
(我还没有尝试过第二种解决方案,但它应该:D工作)
不使用document.write
进行翻译的一种方法 - 并且在关闭 Javascript 或没有翻译时具有文本的额外后果(好处?)是注释需要翻译的元素,并在加载文档后通过更改innerHTML
或textContent
(如果要转义实体)来执行翻译。
您的翻译函数可能是这样的:
function translateAll() {
var dictionary = window.lang[window.curLang];
var elements = document.querySelectorAll("[data-i18n-id]");
for (var i = 0; i < elements.length; i++) {
var el = elements[i];
var translation = dictionary[el.dataset.i18nId]
if (translation) {
el.innerHTML = translation;
}
}
}
您可以执行它,例如onload
:
<body onload="translateAll();">
<h1 data-i18n-id="title">My Title</h1>
</body>
使用 KNOCKOUT.js,方法是将转换密钥存储在计算变量中,然后编写一个翻译服务函数,在哈希表中查找翻译。然后,使此触发器的东西将是一个可观察的,您将使用它对 HTML 标记进行属性绑定,设置 lang
属性。更改此可观察量将触发依赖计算变量自动重新评估和更新文档。如果在这里使用挖空是一种选择,请告诉我,我将设置一个示例。