如何用JS打印屏幕上的所有击键?

时间:2016-02-16 20:53:08

标签: javascript

我正在制作一种刽子手类型的游戏,我在屏幕上显示了按键,但每次按键时它们似乎都会互相覆盖。

如何在屏幕上按顺序显示每个按键?

//Possible words to guess and guesses left
var words = ['jason', 'kaitlyn', 'lora', 'matthew'],
    guessesLeft = 9;

//Computer picks random word to guess
function getItem() {
  document.getElementById("wordGuess").innerHTML = words[Math.floor(Math.random() * words.length)];
}

//This code captures the keypress and prints it out on the screen
document.onkeypress = function(evt) {
  var evt = evt || window.event,
      charCode = evt.keyCode || evt.which,
      lettersGuessed = String.fromCharCode(charCode);

  document.getElementById("lettersGuessed").innerHTML = lettersGuessed;
  document.getElementById("guessesLeft").innerHTML = guessesLeft;

  guessesLeft--;

  // var userGuess = prompt("What word do you guess?");
  // if (words.indexOf(userGuess) > -1){
  //    alert("Your guess is correct.")
  // }else{
  //    alert("Your guess is wrong.")
  // }

  if (guessesLeft === -1) {
    alert("You Loose!");
  }
};

2 个答案:

答案 0 :(得分:4)

在分配lettersGuessed而不是追加它们时会发生覆盖。

Assigning :(行为错误)

document.getElementById("lettersGuessed").innerHTML = lettersGuessed;

Appending :(正确行为)

document.getElementById("lettersGuessed").innerHTML += lettersGuessed;

之后您可以看到以下结果:

//Possible words to guess
 var words = ['jason', 'kaitlyn', 'lora', 'matthew'];



 //Computer picks random word to guess
 function getItem() {
   document.getElementById("wordGuess").innerHTML = words[Math.floor(Math.random() * words.length)];
 }

 //This code captures the keypress and prints it out on the screen
 var guessesLeft = 9;

 document.onkeypress = function(evt) {
   var evt = evt || window.event;
   var charCode = evt.keyCode || evt.which;
   var lettersGuessed = String.fromCharCode(charCode);
   document.getElementById("lettersGuessed").innerHTML += lettersGuessed;
   document.getElementById("guessesLeft").innerHTML = guessesLeft;
   guessesLeft--;

   // var userGuess = prompt("What word do you guess?");
   // if (words.indexOf(userGuess) > -1){
   //  alert("Your guess is correct.")
   // }else{
   //  alert("Your guess is wrong.")
   // }


   if (guessesLeft === -1) {
     alert("You Loose!");
   }
 };
<!-- Example HTML code --->
<div id="wordGuess">abcdefg</div>
<div id="lettersGuessed"></div>
<div id="guessesLeft"></div>

答案 1 :(得分:3)

您在每次按键时都会覆盖#lettersGuessed。你应该做点什么:

document.getElementById("lettersGuessed").innerHTML += lettersGuessed;

但我建议将字母添加到数组中并从那里检查所有内容。