简体   繁体   English

我无法使用 JavaScript 在平方计算器中使用 addEventListener 按下的键进行 console.log 记录?

[英]I can't console.log the key that I pressed with addEventListener in my squaring calculator using JavaScript?

It's not giving errors.它没有给出错误。 I just did the code normally and it didn't work, then I used a function, and then I used a window.onload, and then I used a while loop, and it's still not working.我只是正常做了代码还是不行,然后我用了一个函数,然后我用了一个window.onload,然后我用了一个while循环,还是不行。 The code looks like this:代码如下所示:

JavaScript code: JavaScript 代码:

function square() {
  function foo(n) {
    return n * n;
  }
  window.addEventListener('keypressed', checkKeyPress, false);

  function checkKeyPress(key) {
    if (key.code == '48' || key.code == '49' || key.code == '50' || key.code == '51' || key.code == '52' || key.code == '53' || key.code == '54' || key.code == '55' || key.code == '56' || key.code == '57') {
      console.log(foo(key));
    }
  }
  checkKeyPress('566');
}
window.onload = square();

Also, it isn't giving errors, it's just not working.此外,它没有给出错误,它只是不起作用。 This is from a while ago and I think there was something wrong with the tutorial I watched that while ago.这是前一阵子的,我认为我前段时间看的教程有问题。

Firstly it's not a good practice to declare a function and event listeners inside the function.首先,在函数内部声明函数和事件侦听器不是一个好习惯。 Secondly, in the example which you provided, console.log() don't call, because if statement returns false.其次,在您提供的示例中,console.log() 不会调用,因为 if 语句返回 false。 Thirdly, keypressed is not a valid event.第三,keypressed 不是有效事件。 There are keypress, keyup, keydown.有keypress,keyup,keydown。

A slightly better answer because you could separate these into functions.一个稍微好一点的答案,因为您可以将它们分成函数。 Plus you probably meant keypress or keydown.另外,您可能指的是按键或按键。

function foo(n){
    return n * n;
}

function checkKeyPress(key) {
    if (key.charCode >= 48 && key.charCode <=57) {
        console.log(foo(key.charCode));
    }
}

function square() {
    window.addEventListener('keydown', checkKeyPress, false); 
}

window.onload = square();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM