Home > Article > Web Front-end > `.keyCode` vs. `.which`: Which is the Best Keypress Event Key Identifier?
Keypress Event Key Identification: .keyCode vs. .which
In handling keypress events, developers often face a choice between using .keyCode and .which to determine keystrokes. While both serve the purpose of identifying the pressed key, there are subtle differences and cross-browser compatibility considerations.
Historically, .keyCode was widely used to detect keypresses, but its support is inconsistent across browsers. Some use the character's Unicode code, while others use platform-specific values. This inconsistency can lead to unexpected behavior in cross-browser applications.
On the other hand, .which is a more normalized approach. It returns a standardized value that represents the key's logical identifier, regardless of the browser or platform. However, it may not be supported in older browsers.
To address the potential cross-browser issues, jQuery standardizes the keypress behavior by always using .which. It converts non-standardized values from different browsers to a consistent format, making it a reliable choice for cross-browser compatibility.
If using vanilla JavaScript, developers can ensure browser compatibility by using a combination of both properties, as follows:
<code class="js">var key = 'which' in e ? e.which : e.keyCode;</code>
This code checks if .which is defined in the event object; if so, it uses its value. Otherwise, it falls back to using .keyCode.
Alternatively, a more concise approach can be used:
<code class="js">var key = e.which || e.keyCode || 0;</code>
This expression handles the possibility of .which being 0 by restoring it to that value at the end, utilizing JavaScript's powerful logical OR operator (||).
The above is the detailed content of `.keyCode` vs. `.which`: Which is the Best Keypress Event Key Identifier?. For more information, please follow other related articles on the PHP Chinese website!