#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中文網其他相關文章!