Home >Web Front-end >JS Tutorial >Detailed explanation of how jquery implements the keydown event of div and span
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. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
The above is a piece of text copied from the jquery document. It explains that we can bind the keydown event to the form element because they can get focus, but How to bind p and span?
The answer is the tabindex attribute
Change this attribute in js: jsObj.tabIndex
jquery : $(selector).attr("tabindex",value)
The tabindex attribute of the element is used to define whether the element can obtain focus and whether it can be navigated through continuous focus ( Generally speaking, press the tab key) to get focus, and the order in which you get focus is the same.
Its value must be an integer value.
If it is not set, or the set value is incorrect, follow the convention.
If it is a negative number, the user cannot obtain focus through continuous focus navigation, but can obtain focus in other ways.
If zero, focus can be obtained through continuous focus navigation, ordering by convention.
If it is a positive number, focus can be obtained through continuous focus navigation, and the order is determined according to this value.
p does not get focus by default. You can set the tabindex attribute for it so that it can get focus. You can also bind keyboard events.
Example:
<span id="myspan"></span> js: $("#myspan").attr("tabindex",0); $("#myspan").focus(); $("#myspan").keydown(function() { alert('Handler for .keydown() called.'); });
The above is the detailed content of Detailed explanation of how jquery implements the keydown event of div and span. For more information, please follow other related articles on the PHP Chinese website!