我使用以下代码从Javascript获取keycode值
var whichCode = (window.event) ? e.which : e.keyCode;
但是,除了IE 9之外它工作正常。它在e.which上返回undefined。
答案 0 :(得分:1)
KeyboardEvent.which
从未在Internet Explorer中实现过,在其他版本中被视为已弃用。
MDN解释how to most correctly handle keyboard events:
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.key !== undefined) {
// Handle the event with KeyboardEvent.key and set handled true.
} else if (event.keyIdentifier !== undefined) {
// Handle the event with KeyboardEvent.keyIdentifier and set handled true.
} else if (event.keyCode !== undefined) {
// Handle the event with KeyboardEvent.keyCode and set handled true.
}
if (handled) {
// Suppress "double action" if event handled
event.preventDefault();
}
}, true);
现在,假设您没有处理keyDown事件,您也可以使用
var whichCode = e.charCode !== undefined ? e.charCode : e.keyCode;
请注意,浏览器兼容性为exactly how it is done in jQuery:
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
答案 1 :(得分:0)
此代码在哪里执行?请添加完整的代码。你应该在事件处理程序中使用它! 假设它正确放置,请尝试此
var keycodeValue = e.which || e.keyCode;
其中e是收到的事件