#100daysofMiva 编码挑战的第 8 天,我研究了一个简单的翻译模型,可以将一种语言翻译成另一种语言?
这是JS,这很神奇✨?
此 JavaScript 代码旨在创建一个有趣的交互式语言翻译器!它利用 MyMemory API 在不同语言之间翻译文本,并允许您交换语言、复制翻译,甚至大声朗读文本。 ??
const countries = { /*...*/ }
该对象包含可用的语言及其各自的国家代码。例如,“en-GB”:“English”将语言代码与其名称配对。
selectTag.forEach((tag, id) => { /*...*/ });
此代码使用国家对象中列出的所有语言动态填充下拉菜单。第一个下拉菜单默认为英语(“en-GB”),第二个下拉菜单默认为印地语(“hi-IN”)。
exchageIcon.addEventListener("click", () => { /*...*/ });
单击交换图标允许用户在“从”和“到”字段之间交换文本和所选语言。
translateBtn.addEventListener("click", () => { /*...*/ });
单击“翻译”按钮时,文本将发送到 MyMemory API,翻译后的文本将显示在“待文本”字段中。在等待响应时,会显示“正在翻译...”占位符。
icons.forEach(icon => { /*...*/ });
此部分处理文本转语音和复制功能:
以下是代码的工作原理及其用途的逐步细分:
const countries = { /*...*/ }
const fromText = document.querySelector(".from-text"), toText = document.querySelector(".to-text"), exchageIcon = document.querySelector(".exchange"), selectTag = document.querySelectorAll("select"), icons = document.querySelectorAll(".row i"); translateBtn = document.querySelector("button"),
selectTag.forEach((tag, id) => { for (let country_code in countries) { let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : ""; let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`; tag.insertAdjacentHTML("beforeend", option); } });
exchageIcon.addEventListener("click", () => { let tempText = fromText.value, tempLang = selectTag[0].value; fromText.value = toText.value; toText.value = tempText; selectTag[0].value = selectTag[1].value; selectTag[1].value = tempLang; });
fromText.addEventListener("keyup", () => { if(!fromText.value) { toText.value = ""; } });
translateBtn.addEventListener("click", () => { let text = fromText.value.trim(), translateFrom = selectTag[0].value, translateTo = selectTag[1].value; if(!text) return; toText.setAttribute("placeholder", "Translating..."); let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`; fetch(apiUrl).then(res => res.json()).then(data => { toText.value = data.responseData.translatedText; data.matches.forEach(data => { if(data.id === 0) { toText.value = data.translation; } }); toText.setAttribute("placeholder", "Translation"); }); });
The script allows users to translate text between different languages with a dynamic and interactive interface. Users can select languages, type in their text, translate it with a click, swap languages and text, hear the translation spoken aloud, or copy it to their clipboard.
Enjoy playing with different languages and make your translation journey fun and interactive! ?? Unto the next ?✌?✨
Check it out here
https://app.marvelly.com.ng/100daysofMiva/day-8/
Source code
https://github.com/Marvellye/100daysofMiva/blob/main/Projects%2FDay_8-Simple_language_translator
以上是带 API 的简单语言翻译器的详细内容。更多信息请关注PHP中文网其他相关文章!