我的事件监听器中的函数如何能够在不使用函数参数的情况下接收事件?

发布于 2025-01-13 18:25:35 字数 375 浏览 4 评论 0原文

我正在使用普通 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文