Detecting Key Presses in jQuery: Unraveling the Mystery of 'Which'`
When binding to the "keypress" event in jQuery, a common question arises: how do we determine which key was pressed? Let's explore this in detail.
The traditional approach is to utilize the "keyCode" or "which" property of the event object. However, it's important to note that their availability can vary across browsers. For instance, some browsers like IE and older versions of Firefox may provide "keyCode," while others like Chrome and Safari leverage "which."
To ensure cross-browser compatibility, it's advisable to check for both properties and retrieve the appropriate value. Here's an example:
Moreover, if you're primarily interested in detecting the Enter key, which is always mapped to a non-Unicode character code, both "keyCode" and "which" will serve the purpose effectively.
The above is the detailed content of How Can I Reliably Detect Which Key Was Pressed in jQuery?. For more information, please follow other related articles on the PHP Chinese website!