gpt4 book ai didi

javascript - 尝试使用indexOf方法使字母猜谜游戏的onkeyup函数仅接受字母键

转载 作者:行者123 更新时间:2023-12-02 23:30:00 25 4
gpt4 key购买 nike

尝试使 onkeyup 函数仅接受字母键。 (IndexOf 被注释掉)(我正在使用已经为所有字母键创建的数组)

我目前已经注释掉了一个indexOf

var computerChoices = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"];
var wins = 0;
var losses = 0;
var guessesleft = 9;
var storeduserguess = []

var winsText = document.getElementById("wins-text");
var lossesText = document.getElementById("losses-text");
var guessesleftText = document.getElementById("guessesleft-text");
var userguessesText = document.getElementById("usersguesses-text");
var computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
// I couldn't figure out how to make the onkeyup function only accept alphabet keys (still trying(stackoverflow))
document.onkeyup = function (event) {
// if (computerChoices.indexOf(event) >= 0) {
console.log(event)
var userGuess = event.key;
storeduserguess.push(userGuess);
if (userGuess === computerGuess) {
computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
wins++;
guessesleft = 9;
storeduserguess = [];
}
else if (userGuess !== computerGuess) {
guessesleft--;
}
if (guessesleft === 0) {
computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
losses++;
guessesleft = 9;
storeduserguess = [];
}
winsText.textContent = "Wins: " + wins;
lossesText.textContent = "Losses: " + losses;
guessesleftText.textContent = "Guesses left: " + guessesleft;
userguessesText.textContent = "You guessed: " + storeduserguess;
// open up the console if you want to be a cheater...
console.log(computerGuess);
console.log(userGuess)
// };
};

其他一切正常

最佳答案

将“onkeyup”更改为“onkeypress”

并将此代码添加到函数体的顶部。如果有任何问题请告诉我。

if(computerChoices.indexOf(event.key) === -1) {
return event.preventDefault();
}

关于javascript - 尝试使用indexOf方法使字母猜谜游戏的onkeyup函数仅接受字母键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com