我想用一个带有按钮的英语制作页面,该按钮可以将语言更改为德语。我已经阅读了数千篇有关该主题的文章,但没有得到答案。我知道我绝对不想使用Google Translator API或任何API来做到这一点。我想用纯JS制作。我只想怎么做?使用具有很多行的按钮可以逐一更改元素的文本:function changeLang () { document.getElementById('someid').innerHTML = "some German text"; ... }
还是用const transLang { from = "en" to = "de" ...}
?如果您有任何启动方法,请告诉我。
对于“纯JS”解决方案,换句话说,没有一种通常的解决方案:
一种选择是将翻译存储在每个div上,然后使用进行切换.text()
。请勿将翻译内容编码到javascript中,因为那样将很快无法维护。
function switchLang(lang)
{
$("[data-" + lang + "]").text(function(i, e) {
return $(this).data(lang);
});
}
switchLang("en");
$(".switchlang").click(function() {
// change the button caption here, eg a flag
// UX opinion of whether it should be what it is
// or what it will become
// ie "de" click to make it "de"
// or "de" it's currently "de", click to change it
$(this).text($(this).data("lang"));
// switch to other language based on language on the button
var lang = $(this).data("lang") == "de" ? "en" : "de";
$(this).data("lang", lang);
switchLang(lang)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-de="Um die Nachrichten zu lesen"
data-en="To read the news"></span>,
<span data-de="Übersetzungsdienst nicht verfügbar"
data-en="click here"></span>
<hr/>
<div data-en="no de translation for this line"></div>
<hr/>
<button class='switchlang' data-lang="en">de</button>
然后,您可以轻松添加新语言,而无需更改任何代码(这次使用单独的按钮)
var defaultlang = "en";
function switchLang(lang)
{
$("[data-" + lang + "]").text(function(i, e) {
return $(this).data(lang);
});
}
switchLang("en");
$(".switchlang").click(function() {
switchLang($(this).data("lang"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-de="Um die Nachrichten zu lesen"
data-es="Para leer las noticias"
data-en="To read the news"></span>,
<span data-de="Übersetzungsdienst nicht verfügbar"
data-es="haga clic aquí"
data-en="click here"></span>
<hr/>
<div data-es="no hay traducción para esta línea"
data-en="no de translation for this line"></div>
<hr/>
<button class='switchlang' data-lang="en">en</button>
<button class='switchlang' data-lang="de">de</button>
<button class='switchlang' data-lang="es">es</button>
您可能希望直接在HTML中默认使用该语言,而不是在启动时进行默认设置,例如:
<span data-de="speichern">save</span>
然后将原件.data("en")
放在加载位置。这将消除FOUC(加载页面时的延迟),这对您的情况可能很重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句