提问人:azoundria 提问时间:1/14/2019 最后编辑:Mamunazoundria 更新时间:10/31/2021 访问量:10707
是否可以从 onkeyup 获取密钥代码?[复制]
Is it possible to get the key code from onkeyup? [duplicate]
问:
我知道在使用 JavaScript 或 jQuery 时。我可以在对象上添加一个事件侦听器,以便在按下某个键时调用函数。
但是,如果函数是从 HTML 启动的,如以下示例所示:
function callMyFunction (importantothervalue) {
//How can I get the keycode?
}
<textarea onkeyup="callMyFunction(1);"></textarea>
<textarea onkeyup="callMyFunction(2);"></textarea>
<textarea onkeyup="callMyFunction(3);"></textarea>
有没有办法从这个上下文中检索密钥代码?或者,如果我想获取密钥代码,我是否总是需要创建一个事件处理程序?
有没有办法让我在生成的函数调用中包含 importantothervalue,而无需对 id 或 class 属性中的信息进行编码并从那里提取它?
答:
13赞
Mamun
1/14/2019
#1
使用(或event.key
event.code
)
您可以将 event
传递给可以从中访问属性的函数。key
我建议您查看 KeyboardEvent.key
和 KeyboardEvent.code
的文档
谨防老者keyCode
如果可能,您应该避免使用它;它已被弃用一段时间。相反,如果已实现,则应使用 。不幸的是,有些浏览器仍然没有它,因此您必须小心确保使用所有目标浏览器都支持的浏览器。Google Chrome 和 Safari 已经实现了 ,这是在规范草案中定义的,但不是最终规范。
KeyboardEvent.code
KeyboardEvent.keyIdentifier
例
function callMyFunction (e, importantothervalue) {
console.log(e.key); // ex: "j"
console.log(e.code); // ex: "KeyJ"
console.log(importantothervalue)
}
<textarea onkeyup="callMyFunction(event, 1);"></textarea>
<textarea onkeyup="callMyFunction(event, 2);"></textarea>
<textarea onkeyup="callMyFunction(event, 3);"></textarea>
评论
<textarea onkeyup="callMyFunction(event, 3);"></textarea>