【问题标题】:JavaScript Konami code issues. Code includedJavaScript Konami 代码问题。包含代码
【发布时间】:2021-05-24 07:39:25
【问题描述】:

我对 JavaScript 完全陌生,所以请原谅我缺乏知识。如果有人能告诉我我做错了什么,我将不胜感激(警报“万岁”未触发)。代码如下:

const codes = [
  "ArrowUp",
  "ArrowUp",
  "ArrowDown",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "ArrowLeft",
  "ArrowRight",
  "b",
  "a"
];

let index = 0;

function init() {
  document.body.addEventListener("keydown", (event) => {

    function onKeyDownHandler(e) {
      const key = e.key;

      if (key === codes[index]) {
        index++;

        if (index === codes.length) {
          alert("Hurray");

          index = 0;
        }
      } else {
        index = 0;
      }
    }
  });
}

【问题讨论】:

    标签: javascript dom-events onkeydown


    【解决方案1】:

    函数init() 永远不会被调用,函数onKeyDownHandler() 也不会被调用。一种方法是简单地删除这个内部函数,确保您的 event (e) 与您传递给 addEventListener() 的名称相同。

    以下显示了一个工作示例:

    const codes = [
      "ArrowUp", "ArrowUp", "ArrowDown", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "b", "a"
    ];
    
    let index = 0;
    
    document.addEventListener("keydown", (e) => {
      const key = e.key;
    
      if (key === codes[index]) {
        index++;
    
        if (index === codes.length) {
          alert("Hurray");
    
          index = 0;
        }
      } else {
        index = 0;
      }
    });

    【讨论】:

      【解决方案2】:

      您的init() 可能不会被调用。
      这是一个工作演示:

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <title>hello</title>
          <script>
              const codes = [
                  "ArrowUp",
                  "ArrowUp",
                  "ArrowDown",
                  "ArrowDown",
                  "ArrowLeft",
                  "ArrowRight",
                  "ArrowLeft",
                  "ArrowRight",
                  "b",
                  "a"
              ];
              let index = 0;
              window.onkeydown = function (e) {
                  const key = e.key;
                  if (key === codes[index]) {
                      index++;
                      if (index === codes.length) {
                          alert("Hurray");
                          index = 0;
                      }
                  } else {
                      index = 0;
                  }
              }
      
          </script>
      </head>
      <body>
          hello
      </body>
      </html>  
      

      【讨论】:

        猜你喜欢
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多