【问题标题】:How do I get event.key to display each letter in my html?如何让 event.key 在我的 html 中显示每个字母?
【发布时间】:2017-06-16 02:48:47
【问题描述】:

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

我正在开发一个刽子手游戏,但遇到了一个小问题。 如果 userInput 是我的 if else 语句中的任何其他字母,我可以看到它。问题是我希望它显示该事件,然后显示尚未键控显示的任何其他事件。例如:如果 userInput 是 === "k" 那么 userInput 是 === "b",我希望它在我的 html 中保留 "k" 的显示,然后在它旁边显示 "b"。

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

   document.onkeyup = function(event) {
            var userInput = event.key;

        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");
        }


};

【问题讨论】:

    标签: javascript arrays if-statement innerhtml onkeyup


    【解决方案1】:

    这个:

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

    应该是这样的:

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

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

    而且,您应该真正设置对您将使用的 DOM 元素的缓存引用,这样您就不必在每次代码运行时重新扫描 DOM。它还使代码的读/写更加简单。

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

    另外,考虑接受用户的输入并将其强制为小写,这样当您将他们的猜测与一个字母进行比较时,这是一个不区分大小写的猜测。

    另外,ids 不能以数字开头。

    最后,您的 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>

    【讨论】:

    • 哇!非常感谢您花时间写出来并解释每个项目的作用,这非常有帮助。我也感谢在更正我的代码时提供的额外反馈。
    • @Zamir 不客气(幸运的是我今天下午很无聊!)。请不要忘记给我的帖子投票并将其标记为答案。
    • 绝对是!我看到的唯一问题是我有一个随机单词生成器,那么如果 currentWord !== "taco" 是我的其他随机生成的单词之一呢? var words_array = ["taco", "pizza", "burger" ]; var currentWord = words_array[ Math.floor(Math.random() * words_array.length) ];
    • 在这种情况下,单词将进入一个数组,我的代码需要通过遍历数组并运行我的代码来为数组中的每个单词执行。
    猜你喜欢
    • 2019-03-26
    • 2020-10-10
    • 1970-01-01
    • 2017-09-08
    • 2017-10-13
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多