html 如何使用一个翻译按钮翻译所有输入

dfuffjeb  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(238)

bounty将在6天后过期。回答此问题可获得+100的声誉奖励。Anonymous Girl正在寻找来自声誉良好来源的答案:将是伟大的,如果你部署在这样一个翻译按钮开始翻译所有在点击

我试图翻译所有的输入与各自的翻译语言输出。
当我点击“翻译”按钮,它的工作,但不为各自的语言,输出语言得到改变。
每个输出语言从选择应该是固定的,如西班牙语输出,第二次选择应该是固定的西班牙语,荷兰语输出,第二次选择应该是固定的荷兰语,等等。(每次没有麻烦选择)

第二个选项是输出语言,在HTML <option>标记中应固定该语言

因此,当点击“翻译”它应该翻译所有的相应输入。

const countries = {
  "ar-SA": "Arabic",
  "bn-IN": "Bengali",
  "da-DK": "Danish",
  "de-DE": "German",
  "el-GR": "Greek",
  "en-GB": "English",
  "es-ES": "Spanish",
  "fa-IR": "Persian",
  "fi-FI": "Finnish",
  "fr-FR": "French",
  "gu-IN": "Gujarati",
  "hi-IN": "Hindi",
  "hu-HU": "Hungarian",
  "id-ID": "Indonesian",
  "it-IT": "Italian",
  "ja-JP": "Japanese",
  "kn-IN": "Kannada",
  "ko-KR": "Korean",
  "ku-TR": "Kurdish",
  "la-VA": "Latin",
  "my-MM": "Burmese",
  "ne-NP": "Nepali",
  "nl-NL": "Dutch",
  "ur-PK": "Pakistani",
  "pa-IN": "Panjabi",
  "pl-PL": "Polish",
  "pt-PT": "Portuguese",
  "ro-RO": "Romanian",
  "ru-RU": "Russian",
  "sq-AL": "Albanian",
  "sr-RS": "Serbian",
  "sv-SE": "Swedish",
  "ta-LK": "Tamil",
  "te-IN": "Telugu",
  "th-TH": "Thai",
  "tr-TR": "Turkish",
  "uk-UA": "Ukrainian",
  "vi-VN": "Vietnamese"
};
const fromText = document.querySelectorAll(".from-text", ".from-text2"),
  toText = document.querySelectorAll(".to-text", ".to-text2"),
  selectTag = document.querySelectorAll("select");

(translateBtn = document.getElementById("btn4all")),
  selectTag.forEach((tag, id) => {
    for (let country_code in countries) {
      let selected =
        id == 0
          ? country_code == "en-GB"
            ? "selected"
            : ""
          : country_code == "es-ES"
          ? "selected"
          : "";
      let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`;
      tag.insertAdjacentHTML("beforeend", option);
    }
  });

fromText.forEach((el, index) => {
  if(!el.value){
    toText[index].value = "";
  }
});
function translate(fromEl, toEl, language){
    let text = fromEl.value.trim();
    let translateFrom = "en-GB"; //I've hard-coded this as there's only 1 select tag per row? Something to consider
    let translateTo = language.value;
    
    if(!text){
        return;
    }

    toEl.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) {
                    toEl.value = data.translation;
                }
            });
            toEl.setAttribute("placeholder", "Translation");
        });
}

translateBtn.addEventListener("click", () => {
    //this button is the first button on the page so we'll hard-code the first elements for now
    translate(fromText[0], toText[0], selectTag[0]);
});

document.getElementById("btn4all").addEventListener("click", () => {
    //here I am assuming that there are matching numbers of from, to, and language dropdowns - worth considering

    for(let i = 0; i < fromText.length; i++){
        translate(fromText[i], toText[i], selectTag[i]);
    }
});
.radioact {
  display: inline-flex;
}
.input-group {
  display: flex;
  align-content: stretch;
  width: 75.666667%;
  margin-left: 17%;
  margin-bottom: 15px;
}

.btn3 {
  cursor: pointer;
  background: #05203e;
  color: white;
  width: 150px;
  padding: 20px 30px;
  border-radius: 4px;
}
.transs {
  list-style: none;
  margin-bottom: 0px;
  width: 15%;
  margin-right: 35px;
}
<div class="input-group">

  <input type="text" value="" class="to-text form-control" name="name_eslang" placeholder="Spanish Word">

  <input spellcheck="false" value="Translate word" id="translatename" class="from-text" placeholder="Type to Translate">

  <ul class="transs">
    <li class="row from"><select></select>
    </li>
    <li class="row to"><select></select>
    </li>
  </ul>

</div>

<div class="input-group">

  <input type="text" value="" class="to-text form-control" name="name_eslang" placeholder="Dutch Word">

  <input spellcheck="false" value="Translate word" id="translatename" class="from-text" placeholder="Type to Translate">

  <ul class="transs">
    <li class="row from"><select></select>
    </li>

    <li class="row to">
      <select>
      </select>
    </li>
  </ul>
</div>

<div class="input-group">

  <input type="text" value="" class="to-text form-control" name="name_eslang" placeholder="Hindi Word">

  <input spellcheck="false" value="Translate word" id="translatename" class="from-text" placeholder="Type to Translate">

  <ul class="transs">
    <li class="row from"><select></select>
    </li>
    <li class="row to">
      <select>
      </select>
    </li>
  </ul>
</div>

<div class="input-group">

  <input type="text" value="" class="to-text form-control" name="name_eslang" placeholder="Portuguese Word">

  <input spellcheck="false" value="Translate word" id="translatename" class="from-text" placeholder="Type to Translate">

  <ul class="transs">
    <li class="row from"><select></select>
    </li>
    <li class="row to">
      <select>
      </select>
    </li>
  </ul>
</div>
<br>
<span id="btn4all" class="btn3">Translate</span>
vxf3dgd4

vxf3dgd41#

首先,我建议将fromText = document.querySelector(更改为fromText = document.querySelectorAll(,它现在返回所有匹配元素的数组-对toText也做同样的操作。
我建议将translateBtn.addEventListener中的代码拆分到它自己的函数中

function translate(fromEl, toEl, languageFrom, languageTo){
    let text = fromEl.value.trim();
    let translateFrom = languageFrom.value
    let translateTo = languageTo.value;
    
    if(!text){
        return;
    }

    if(languageFrom == languageTo){
        alert("Languages must be different!");
        return;
    }

    toEl.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) {
                    toEl.value = data.translation;
                }
            });
            toEl.setAttribute("placeholder", "Translation");
        });
}

然后我们可以重用它,或者添加额外的translate按钮,或者用于我们的“translate all”按钮。

translateBtn.addEventListener("click", () => {
    //this button is the first button on the page so we'll hard-code the first elements for now
    translate(fromText[0], toText[0], selectTag[0], selectTag[1]);
});

或者,添加更多的按钮将给予如下代码:

document.querySelectorAll(".btn3").forEach((el, index) => {
    el.addEventListener("click", () => {
        translate(fromText[i], toText[i], selectTag[i * 2], selectTag[(i * 2) + 1]);
    });
});

无论如何,现在我们已经分离了translate函数,我们可以启动那个神奇的“translate all”函数了--它实际上看起来非常类似于我们的代码,因为它有许多translate按钮!

document.getElementById("btn4all").addEventListener("click", () => {
    //here I am assuming that there are matching numbers of from, to, and language dropdowns - worth considering

    for(let i = 0; i < fromText.length; i++){
        translate(fromText[i], toText[i], selectTag[i * 2], selectTag[(i * 2) + 1]);
    }
});

(as顺便说一句,可能值得检查一下您的ID和类-.btn3#btn4all并不是最具描述性的名称!请考虑.btn-translate(或.btn.translate)和#translateAll(或#translateAll.btn))
正如评论中提到的,fromText现在变成了一个数组--所以你的事件监听器需要看起来不同。

//an exact replacement - only listening for the first element
fromText[0].addEventListener("keyup", () => {
  if (!fromText[0].value) {
    toText[0].value = "";
  }
});

//OR - listening for all
fromText.forEach((el, index) => {
  if(!el.value){
    toText[index].value = "";
  }
});

相关问题