简体   繁体   中英

What does this statement on keydown event mean?

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.

I am confused because I thought this is the case with every event. A click event can be attached to a list or a paragraph but will be sent only to element that has focus. Am I missing something here? Also, what does the event is only sent to the element that has the focus exactly mean?

Consider this example:

 $('.example').on('keydown', function(e){ alert($(this).data('name')) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class='example' data-name='input1'> <input class='example' data-name='input2'> <input class='example' data-name='input3'> 

The keydown event is bound to all 3 input elements, however, the name is only returned for the element the event occurs on, ie, the element which has focus.

When you click on anything on a website (or touch anything on mobile, or use Tab to jump between elements) you set the focus to that element. For example clicking on a link sets the focus on it (and the link is sometimes highlighted then), clicking on an input field gives you the little cursor in there. This is essentially what focus means.

By sending an event only to the element that has the focus you can avoid a situation, where you have several input fields on a website and by typing in one you type in all the others at the same time, since the keydown event is only sent to the one, that has the focus (in essence - that you clicked before).

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