簡體   English   中英

如何檢查輸入字符串是否包含與 Javascript 中 API 信息匹配的單詞?

[英]How to check if the input string consists of a word matches with the information from API in Javascript?

預期結果:用戶從鍵盤輸入任何字符。 然后它們將用於檢查輸入的字符串是否是 Dictionary API 中的單詞。 如果它們相互匹配,則字符串將位於<p>元素中。 如果沒有,那么輸入的字符串將通過anotherFunction()

問題:

  1. 是否有可能通過keyboard.event而不是在<input> / <textarea>中, fetchApi()能夠從字符串中搜索一個真實的單詞,而不是每個輸入的字符? (就像我不希望那樣,直到用戶輸入單詞並按Enter ,然后 API 開始啟動)
  2. 如果是這樣,我可以在代碼中進行哪些更改以獲得上述預期結果?

再次感謝您,一次又一次。 非常感謝!

var characters = '';
var text = document.getElementById("text");
var word = result[arg0].word;

document.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    fetchApi(input.key);
  }
});

function fetchApi(word) {
  let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
  fetch(url).then(res => res.json()).then(result => data(result, word));
  }

function data(result, word) {
  if (input.key == word) {
      characters += input.key;
      text.innerHTML = characters;
  }
  else {
      text.innerHTML = anotherFunction();
  }
}
<p id="text"></p>

我希望我能正確理解您的問題,但我認為您想要的是:

  1. 僅偵聽輸入字段中的關鍵事件,而不是整個文檔。 為此,只需將事件偵聽器添加到所需的<input><textarea>而不是document 在這里解釋
text.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    fetchApi(input.key);
  }
});
  1. 您還可以收聽Enter鍵。 為此,您可以簡單地獲取<input>的值並將其直接發送到 API ( text.value )。 或者,如果您想過濾之前的字符(並從現有解決方案中更改盡可能少的代碼),您也可以將characters發送給它。 (就像下面的代碼)
let inputWord = ""
text.addEventListener('keydown', function(input) {
  if (input.key >= 'a' && input.key <= 'z') {
    inputWord += input.key; // add each character to string if it's between a-z
  } else if (input.key === "Enter") { // on enter fetch the entire inputWord
    fetchApi(inputWord);
    inputWord = "" // clear inputWord after Enter (but not in <input>)
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM