[英]Check if a word in a string matches a word in an array and if so remove it from the string
[英]How to check if the input string consists of a word matches with the information from API in Javascript?
預期結果:用戶從鍵盤輸入任何字符。 然后它們將用於檢查輸入的字符串是否是 Dictionary API 中的單詞。 如果它們相互匹配,則字符串將位於<p>
元素中。 如果沒有,那么輸入的字符串將通過anotherFunction()
。
問題:
keyboard.event
而不是在<input>
/ <textarea>
中, fetchApi()
能夠從字符串中搜索一個真實的單詞,而不是每個輸入的字符? (就像我不希望那樣,直到用戶輸入單詞並按Enter
,然后 API 開始啟動)再次感謝您,一次又一次。 非常感謝!
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>
我希望我能正確理解您的問題,但我認為您想要的是:
<input>
或<textarea>
而不是document
。 在這里解釋text.addEventListener('keydown', function(input) {
if (input.key >= 'a' && input.key <= 'z') {
fetchApi(input.key);
}
});
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.