简体   繁体   English

eventListener无法读取keyCode

[英]eventListener can't read keyCode

So I'm working on a game that will accept user input (up down left right arrow keys). 所以我正在开发一款接受用户输入的游戏(向上向下左箭头键)。 To do so, I will add an event listener that will check when the user presses said keys. 为此,我将添加一个事件监听器,用于检查用户何时按下所述键。 I have it set up in the following way: 我按以下方式设置它:

function gameStart(){

    //Generates four random numbers on board
    for(gameStart_i = 0; gameStart_i < 4; gameStart_i++){
        generateNumber();
    }

    document.getElementById("start_button").innerHTML = "Reset Game";
    document.getElementById("start_button").setAttribute('onclick', 'reset()');
    document.getElementById("start_button").id = 'reset_button';

    var board = document.getElementById("game_background");


    console.log("1");
    board.addEventListener("keydown", inputListen(), false);
    console.log("1.1");
}

function inputListen(e){
    console.log("2");
    var code = e.keyCode;
    switch(code){
        case 37:
            alert("left");
            break;
        case 38:
            alert("up");
            break;
        case 39:
            alert("right");
            break;
        case 40:
            alert("down");
            break;
    }
}

This seems in line with how tutorials show it. 这看起来与教程如何显示一致。 However, some tutorials change the addEventListener line with something that would look like this: 但是,有些教程会使用如下所示的内容更改addEventListener行:

  board.addEventListener("keydown", inputListen, false); //removes the () after the function

However that doesn't seem to work for me when I look into my console. 然而,当我查看我的控制台时,这似乎对我不起作用。

When I run my code my console gives me the following error: 当我运行我的代码时,我的控制台给了我以下错误:

  1
  2
Uncaught TypeError: Cannot read property 'keyCode' of undefined
    at inputListen (script.js:86)
    at gameStart (script.js:16)
    at HTMLButtonElement.onclick (2048Game.html:114)

I think it's because I don't pass any parameters to my function, but none of the online tutorials pass paraements in their addEventListener statement. 我认为这是因为我没有将任何参数传递给我的函数,但是没有一个在线教程在其addEventListener语句中传递paraements。

Thank you, Alex 谢谢,Alex

The proper way to do this is indeed to remove the () after inputListen . 这样做的正确方法确实是在inputListen之后删除() Using the () immediately calls the function, which then gives you aforementioned Cannot read property 'keycode' of undefined since no input parameters were given. 使用()立即调用该函数,然后由于没有给出输入参数,因此给出了前面提到的Cannot read property 'keycode' of undefined

You should have also received the error in the console between the two console.log lines, which proves the error came from the addEventListener line. 您应该在两个console.log行之间的控制台中收到错误,这证明错误来自addEventListener行。

You want to pass the function without calling it using the line you posted: 您希望在不使用您发布的行调用它的情况下传递函数:

board.addEventListener("keydown", inputListen, false); //removes the () after the function

Take a look at this JSFiddle : 看看这个JSFiddle

function gameStart(){
  console.log("before");
  document.getElementById("game_background").addEventListener("keydown", inputListen, false);
  console.log("after");
}

This should print out to the console 这应打印到控制台

before
after

And then nothing else until it detects a keydown . 然后在检测到keydown之前别无其他。

It also matters what kind of element you bind this to. 同样重要的是你绑定它的元素。 An element such as <input> will have no trouble here, but normal non-focusable elements will need the tabindex attribute in order to be focused and respond to a keydown : <input>这样的元素在这里没有问题,但是普通的不可聚焦元素需要tabindex属性才能被聚焦并响应keydown

<div id="game_background" tabindex="-1">
</div>

You'll need to click the element once to focus onto it, then your events should be captured. 您需要单击该元素一次以关注它,然后应捕获您的事件。 More info at this answer . 更多信息在这个答案

  1. Yes drop the () , you are using the function itself to the event listener, not the result of the function call. 是删除() ,您正在将函数本身用于事件侦听器,而不是函数调用的结果。

  2. The keydown event is likely not sent to an arbitrary <div> in the page. keydown事件很可能不会发送到页面中的任意<div> Add the event listener to the window itself instead, if you don't want the user to manually click to focus on it. 如果您不希望用户手动单击以关注它,则将事件侦听器添加到窗口本身。

window.addEventListener('keydown', inputListen);

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

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