我的事件监听器中的函数如何能够在不使用函数参数的情况下接收事件?
我正在使用普通 JavaScript 开发一个非常简单的游戏,而我现在看到的行为与我在函数方面学到的一切背道而驰。我不明白为什么可以在没有调用函数时使用的常用括号的情况下调用 getInput
。事实上,当我像这样添加括号:document.addEventListener("keydown", getInput());
时,它根本不起作用。
那么,在不将事件密钥作为参数传递的情况下,我如何能够接收和打印事件密钥呢?
document.addEventListener("keydown", getInput);
function getInput() {
console.log(event.key);
}
I'm working on a very simple game using vanilla JavaScript and the behavior I'm seeing right now goes against everything I've learned about with functions. I don't understand why getInput
can be called without the usual parenthesis that you'd use when calling functions. In fact, when I add parenthesis like this: document.addEventListener("keydown", getInput());
, it doesn't work at all.
So then, how am I able to receive and print the event key without it having been passed as a parameter?
document.addEventListener("keydown", getInput);
function getInput() {
console.log(event.key);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论