Javascript:带有 onkeydown 的 addEventListener 似乎不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2369139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:58:39 来源:igfitidea点击:
Javascript: addEventListener with onkeydown doesn't seem to work
提问by chimerical
If you replace "onkeydown" with "click", it reacts, at least.
如果您将“onkeydown”替换为“click”,它至少会做出反应。
<input id="yourinput" type="text" />
<script type="text/javascript">
document.getElementById("yourinput").addEventListener("onkeydown", keyDownTextField, false);
function keyDownTextField() {
alert("functional");
if(keycode==13) {
alert("You hit the enter key.");
}
else{
alert("Oh no you didn't.");
}
}
</script>
回答by CMS
The event type should be "keydown", notice that you don't need the onprefix:
事件类型应该是 "keydown",注意你不需要on前缀:
element.addEventListener("keydown", keyDownTextField, false);
Note also that you should get the keyCodefrom the event object in your handler:
另请注意,您应该keyCode从处理程序中的事件对象中获取:
function keyDownTextField (e) {
var keyCode = e.keyCode;
//...
}
Check an example here.
在此处查看示例。

