gpt4 book ai didi

javascript - 如何在 javascript 中获取用户输入并在页面上显示此输入?

转载 作者:行者123 更新时间:2023-11-30 14:07:51 25 4
gpt4 key购买 nike

我是 Java 的新手,正在尝试创建一个模拟刽子手的游戏。我试图在用户在键盘上输入后从他们那里获取字母。然而,当我输入一些东西时,它没有任何区别,它不会输出它是正确的还是不正确的。我想我可能没有在我的 guessLetter() 函数中正确使用该事件,我们将不胜感激任何帮助。

window.addEventListener("DOMContentLoaded", function() {
var word = ['taco'];

let randNum = Math.floor(Math.random() * word.length);
let chosenWord = word[randNum];
let underScore = [];

let docUnderScore = document.getElementsByClassName('underScore');
let docRightGuess = document.getElementsByClassName('rightGuess');
let docWrongGuess = document.getElementsByClassName('wrongGuess');

console.log(chosenWord); //lets grader cheat

let generateUnderscore = () => {
for (let i = 0; i < chosenWord.length; i++) {
underScore.push('_');
}
return underScore;
}


document.onkeyup = function guessLetter(event) {
let letter = String.fromCharCode(event.keyCode || event.code).toLowerCase();

if (chosenWord.indexOf(letter) > -1) {
rightWord.push(letter);
underScore[chosenWord.indexOf(letter)] = letter;
docUnderScore[0].innerHTML = underScore.join(' ');
docRightGuess[0].innerHTML = rightWord;
if (underScore.join('') === chosenWord) {
alert('CONGRATS! YOU WIN!!!');
} else {
wrongWord.push(letter);
docWrongGuess[0].innerHTML = wrongWord;
}
}
underScore[0].innerHTML = generateUnderscore().join(' ');

}
});
<!DOCTYPE html>
<html>

<head>
<h1> Hangman </h1>
<div id="guesses">
<div class="letter" id="letter" </div>
</div>
</head>

<body>
</body>
<div class="container">
<div class="underScore">_ _ _ _</div>
<div class="rightGuess"> right guess </div>
<div class="wrongGuess"> wrong guess </div>
</div>

</html>

最佳答案

在 JS 控制台中,由于未定义 rightWordwrongWord 变量而引发 ReferenceErrors

关于javascript - 如何在 javascript 中获取用户输入并在页面上显示此输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55073433/

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