Example
shows which key was pressed:
$("input").keydown(function(event){
$("div").html("Key: " event.which);
});
Try it yourself
Definition and Usage
The which attribute indicates which key or button was pressed.
Syntax
event.which Parameter Description
event Required. Specifies the events to be checked. The event parameter comes from the event binding function.
jQuery discards the standard button attribute in favor of which, which is a bit puzzling.
which is introduced by Firefox and is not supported by IE. The original intention of which is to obtain the key value (keyCode) of the keyboard.
Which in jQuery can be the key value of the keyboard or the key value of the mouse.
That is, which can be used when determining which key of the keyboard the user pressed, and which can also be used when determining which key of the mouse the user pressed. It serves two purposes.
Source code:
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event. keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
Standard buttons use 0,1,2 to represent the left, middle, and right mouse buttons. jQuery's which uses 1,2,3.
Another unpleasant thing is that the jQuery document event.which does not mention that which can represent the mouse button value, only the keyboard button value is mentioned.
The comments in the source code are also misleading.
// Add which for click: 1 === left; 2 === middle; 3 === right
Note that it is click here. It is easy for people to use the click event, but in fact the click event is wrong.
Try using the click event below:
< ;!DOCTYPE html>
< ;body>