即使我在 Javascript 中只按一次按键,按键事件仍被拦截 40 次
我想通过以下代码用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如开发人员 Mozilla 文档所述,不再支持按键功能。
有了这个小上下文,我找不到问题,您可以首先使用 'keydown' 事件更改它,看看它是否有效。
As documented by the Developer Mozilla documentation, keypress feature is no longer supported.
With this little context I cannot find the problem, you could start by changing it with the 'keydown' event and see if it works.
这是我的解决方案。我将代码从构造函数中取出,该构造函数连续地将其放在react钩中。
This is my solution. I took the code away from the constructor that is called continuously an put it in a react hook.