使用自定义回调添加事件监听器?

时间:2022-06-01 20:38:43

So I am making a game and I want everything to be dynamic so I can use it to make other things. I'm trying to set the event listener callback to a custom callback. I'm just testing it with keydown for now, but when I push my keys, nothing outputs in the console:

所以我在做一个游戏,我希望一切都是动态的所以我可以用它来做其他的事情。我尝试将事件监听器回调到一个自定义回调。我现在只是用按键来测试它,但是当我按下按键时,控制台上没有输出:

Here is the registerKeyListener function:

这里是registerKeyListener函数:

function registerKeyListener(id, type, callback){
    document.getElementById(id).addEventListener(type, callback, false);
}

Here is how I call it:

下面是我如何称呼它:

registerKeyListener("game", "keyDown", move);

Where move is:

移动在哪里:

function move(){
    console.log("move function called");
}

1 个解决方案

#1


3  

Your function works. The event is keydown, not keyDown.

你的函数。事件是关键,而不是关键。

See demo of your code.

参见您的代码演示。

Though there can be events with upper case letters, all the usual ones are lower case only. Check here for reference: https://developer.mozilla.org/en-US/docs/Web/Reference/Events

虽然可以用大写字母表示事件,但通常情况下只有小写字母。检查这里,以供参考:https://developer.mozilla.org/en-US/docs/Web/Reference/Events。

#1


3  

Your function works. The event is keydown, not keyDown.

你的函数。事件是关键,而不是关键。

See demo of your code.

参见您的代码演示。

Though there can be events with upper case letters, all the usual ones are lower case only. Check here for reference: https://developer.mozilla.org/en-US/docs/Web/Reference/Events

虽然可以用大写字母表示事件,但通常情况下只有小写字母。检查这里,以供参考:https://developer.mozilla.org/en-US/docs/Web/Reference/Events。