我想在我的网站中创建 1 个法语页面(其余页面为英语),因此我正在研究 jQuery 来执行此操作。这是最好的方法吗?
我希望它在页面加载时触发,这将在多个浏览器上工作,目前我正在使用 HTML 替换。
jQuery(function($) {
$("body").children().each(function() {
$(this).html($(this).html().replace(/Download/g, "FranceDownload"));
});
$("body").children().each(function() {
$(this).html($(this).html().replace(/Document/g, "FranceDocument"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Onload this document will Translate to French.<br><br>
<div>Download - Document</div>
我创建了以下代码笔来展示这一点:https://codepen.io/scottYg55/pen/dybOdgw
这会根据需要更改文档语言,因为用户将手动编码他们想要更改的单词。
有更好的方法吗?我需要每次都触发 "$("body").children().each(function ()"吗?
谢谢
最佳答案
如果您不想使用插件,并且只需要翻译文本内容,那么我认为您最好只创建一个小词典,然后将其用于您的页面。 (好的,它也支持 HTML。)
我用一个切换按钮模仿了 onload,但是该函数本身可以在您的代码中的任何地方使用(它“看到”dict 对象和 lang 变量)。
您唯一需要的标记是包含文本和 dict 对象中的元素的元素的 data-translate 属性。
const dict = {
"0": {
en: "Download - Document",
fr: "Télécharger - Document"
},
"1": {
en: "It's not a document",
fr: "Ce n'est pas un document"
},
"2": {
en: "Translate this, while you<br />are fast asleep.",
fr: "Traduisez ceci pendant que<br />vous êtes endormi."
}
}
let lang = 'en'
const btnLang = document.getElementById('toggleLang')
// click event: toggle language
btnLang.addEventListener('click', function(e) {
lang = lang === 'en' ? 'fr' : 'en'
toggleLang(lang)
})
// toggle language (using lang variable and dict object)
function toggleLang(lang) {
const toTranslate = document.querySelectorAll("[data-translate]")
toTranslate.forEach(e => {
e.innerHTML = dict[e.getAttribute('data-translate')][lang]
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Onload this document will Translate to French.<br><br>
<button id="toggleLang">Toggle language</button>
<div data-translate="0">Download - Document</div><br><br>
<div data-translate="1">It's not a document</div><br><br>
<div data-translate="2">Translate this, while you<br />are fast asleep.</div>
虽然这是一个简单的解决方案(并且在字节方面确实很小),但它并非万无一失:您必须处理 dict 对象(因此它具有在HTML),并且所有元素都具有您想要的所有语言变体。
但如果您想获得更彻底的解决方案,我建议您查看用于 jQuery 的 i18n(https://blog.lokalise.co/localizing-apps-jquery/ 或 https://dzone.com/articles/localize-your-app-with-jqueryi18n)。 i18n 是相当国际化(或本地化)的标准,您可能会在很多“地方”遇到它:Wordpress (WPML)、JS 框架(如 VueJS:https://www.npmjs.com/package/vue-i18n)。所以,如果你在这种情况下使用它,你可能会学到一些以后可以派上用场的东西。 :)
关于javascript - 语言更改加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57595133/