简体   繁体   中英

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. By adding e.preventDefault() seems to fix the issue but I want to understand why it's behaving that way in the first place. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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