即使我在 Javascript 中只按一次按键,按键事件仍被拦截 40 次

发布于 2025-01-18 11:19:48 字数 299 浏览 1 评论 0原文

我想通过以下代码用javascript拦截事件“keypress”:

document.addEventListener("keypress", (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
}

该代码实际上有效。问题是,即使我按 a 字母一次,字符串“You press the key a”也会在我的控制台中打印 40 次。它应该是 keydown 的行为,而不是 keypress。

I want to intercept the event "keypress" with javascript through the following code:

document.addEventListener("keypress", (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
}

The code actually works. The problem is that even though I press the a letter once, the string "You press the key a" is printed in my console 40 times. It should be the behaviour of keydown, not keypress.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

信愁 2025-01-25 11:19:48

正如开发人员 Mozilla 文档所述,不再支持按键功能。

尽管某些浏览器可能仍然支持它,但它可能已从相关网络标准中删除,可能正在被删除,或者可能仅出于兼容性目的而保留。避免使用它,并尽可能更新现有代码。

有了这个小上下文,我找不到问题,您可以首先使用 'keydown' 事件更改它,看看它是否有效。

As documented by the Developer Mozilla documentation, keypress feature is no longer supported.

Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible.

With this little context I cannot find the problem, you could start by changing it with the 'keydown' event and see if it works.

咆哮 2025-01-25 11:19:48

这是我的解决方案。我将代码从构造函数中取出,该构造函数连续地将其放在react钩中。

const onKeyPress = (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
};

useEffect(() => {
    document.addEventListener("keypress", onKeyPress);
    return () => {
        document.removeEventListener("keypress", onKeyPress);
    }
}, []);

This is my solution. I took the code away from the constructor that is called continuously an put it in a react hook.

const onKeyPress = (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
};

useEffect(() => {
    document.addEventListener("keypress", onKeyPress);
    return () => {
        document.removeEventListener("keypress", onKeyPress);
    }
}, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文