简体   繁体   English

当多个事件附加到按钮时,Enter键会触发click事件和keypress

[英]Enter key fires both click event and keypress when multiple events are attached to button

I have two events attached to a button and when I press a key while the button is on focus both keypress and click events are fired. 我将两个事件附加到一个按钮上,当按钮处于焦点状态时按下一个键时,会同时触发按键和单击事件。 However, if I click the button only the click event is fired. 但是,如果我单击按钮,则仅触发click事件。 By adding e.preventDefault() seems to fix the issue but I want to understand why it's behaving that way in the first place. 通过添加e.preventDefault()似乎可以解决此问题,但我想了解为什么它首先会采用这种方式。 Apologies if this is a duplicate but I couldn't find a relevant answer apart from this one but the explanation isn't clear enough there. 抱歉,如果这是重复的,但除了这个我找不到其他答案,但那里的解释不够清楚。 Many thanks. 非常感谢。

 $('.btn').on('click keypress',function(e){ console.log(e.type); }); 
 <button type="button" class="btn" >click me</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

On button focus 按键焦点

if you pressed any key except (space and enter) only the keypress event will fire 如果您按了(空格和Enter)以外的任何键,则仅会触发keypress事件

But

if you focus the button and press space or enter this will fire both the events because this is a browser default behavior also for this same reason e.preventDefault() solved the problem for you. 如果将焦点放在按钮上并按空格或输入,则将触发两个事件,因为这也是浏览器的默认行为,也是出于同样的原因e.preventDefault()为您解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM