如何让 event.key 显示我的 html 中的每个字母?

How do I get event.key to display each letter in my html?

感谢您抽出宝贵时间提供帮助!

我正在开发一个刽子手游戏,运行遇到了一个小问题。 我能够看到 userInput,如果它是我的 if else 语句中下面的任何其他字母。问题是我希望它显示该事件,然后显示尚未键控显示的任何其他事件。例如:如果 userInput 为 === "k",则 userInput 为 === "b",我希望它在我的 html 中保留 "k" 的显示,然后并排显示它 "b"。

此外,如果有更好的方法来使用循环或使用 forEach 编写我的 if else 语句,那将会很有帮助。我对这些概念很陌生。 再次感谢。

   document.onkeyup = function(event) {
            var userInput = event.key;</p>

        if (currentWord === "taco"){

            if (userInput === "t" ) { 

                document.getElementById("1st-letter").innerHTML = userInput;
            }

            else if (userInput === "a") {

                document.getElementById("2nd-letter").innerHTML = userInput;

                }

            else if (userInput === "c") {

                document.getElementById("3rd-letter").innerHTML = userInput;

            }

            else if (userInput === "o") {
                document.getElementById("4th-letter").innerHTML = userInput;
            }


            else {
                document.getElementById("incorrect-letters").innerHTML = userInput;

            }
        }
        else {
            alert("Code is working");
        }


};

这个:

document.getElementById("incorrect-letters").innerHTML = userInput;

应该是这样的:

document.getElementById("incorrect-letters").innerHTML =
   document.getElementById("incorrect-letters").innerHTML +userInput;

这样您就不会完全替换元素的 innerHTML,而是添加元素。

而且,您真的应该设置对要使用的 DOM 元素的缓存引用,这样您就不必每次都 re-scan DOM代码运行。它还使代码更简单 read/write.

而且,您可能不想使用 key,它会为您提供用户按下的实际键,而不是按键产生的字符。相反,您应该使用 keyCodecodekeyCode 得到广泛支持,但正在被尚未得到广泛支持的 code 取代)。

此外,考虑接受用户的输入并将其强制为小写,以便当您将他们的猜测与字母进行比较时,这是一个 case-insensitive 猜测。

此外,id不能以数字开头。

最后,您的 if/`else' 代码可以工作,但它可以简化,您将在下面的示例中看到:

// Wait until the DOM is fully loaded and then run the function
window.addEventListener("DOMContentLoaded", function(){

    // Set up variable to cache reference to the DOM elements we'll be using
    var incorrectLetters = document.getElementById("incorrect-letters");
    var guesses = document.getElementById("guesses");
  
    // Find all the letter element containers:
    var containers = document.querySelectorAll(".letter");
    var foundCount = 0;

    // Set up the secret word
    var currentWord = "taco";
 
    document.onkeyup = function(event) {
   
      // event.keyCode and event.code return the numeric code for the character 
      // they produce. When passed to String.fromCharCode(), we get the actual
      // character that was produced by the key input, but this excludes keystrokes
      // that don't produce a visible character (space, backspace, tab, enter, etc.)
      // From there, we convert that character to lower-case.
      var userInput = String.fromCharCode(event.keyCode || event.code).toLowerCase();
      var found = false;

      // Check input to see if it is in the secret word array and, if so,
      // print the input in the correct position
      
      // Loop through each letter in the array
      for(var i = 0; i < currentWord.length; ++i){
        
        // Check the input against the current letter we're looping over
        if(userInput === currentWord[i]){
          
          // We have a match, put the letter in the container that is in the same
          // position in the array as it is in the word
          containers[i].textContent = userInput;
          
          // Flag that we have a matched letter and up the matched letter count
          found = true;
          foundCount++;
        }
      }
      
      // If all letters have been found, change display to show a winner
      if(foundCount === containers.length){
         guesses.classList.add("winner");
      }
      
      // If the input wasn't found after looping, write it in the bad guesses area
      if(!found) { incorrectLetters.innerHTML = incorrectLetters.innerHTML + userInput; }

    };
  
});
#incorrect-letters { 
  border:2px dashed blue; 
  background-color:rgba(100,200,100,.75); 
  height:1.5em; 
  font-family:monospaced;
  letter-spacing:.75em;
  font-weight:bold;
  line-height:1.5em;
  font-size:1.5em;
  padding:0 10px;
}

.letter { 
  float:left; 
  border-bottom:2px solid black;
  font-size:2em;
  color:green;
  width:2em;
  height:1em;
  margin-right:1em;
  text-align:center;
}

.winner {
  background-color:yellow;
  border:5px solid green;
  height:2.5em;
}
<p>Click on the document and type your letter guess</p>
<p>Bad guesses:</p>
<div id="incorrect-letters"></div>

<p>Correct guesses:</p>
<div id="guesses">
  <div class="letter" id="firstLetter"></div>
  <div class="letter" id="secondLetter"></div>
  <div class="letter" id="thirdLletter"></div>
  <div class="letter" id="fourthLetter"></div>
</div>