javascript Event.keyCode 不适用于“输入” - 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21159930/
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-10-27 20:14:48  来源:igfitidea点击:

Event.keyCode doesn't work with 'on input' - undefined

javascriptjqueryeventsinput

提问by Paladini

Currently I'm working on a feature for a project and event.keyCode appears doesn't work for "on input" trigger. I'm using Google Chrome 31 and jQuery 1.10.2.

目前我正在为一个项目开发一个功能,并且 event.keyCode 出现不适用于“输入”触发器。我使用的是 Google Chrome 31 和 jQuery 1.10.2。

Here's what I tried inside my method:

这是我在我的方法中尝试的内容:

input.on('input', function(event){
    console.log("event.charCode: " + event.charCode);
    console.log("event.keyCode: " + event.keyCode);
    console.log("event.which: " + event.which);
    console.log("window.event ? event.keyCode : event.which: " + window.event ? event.keyCode : event.which);
});

enter image description here

在此处输入图片说明

I get undefinedfor all this methods. Am I doing something wrong or this is a jQuery / Javascript issue? Here you can find the fiddle.

我得到undefined了所有这些方法。我做错了什么还是这是一个 jQuery / Javascript 问题?在这里你可以找到小提琴

I want that my input fires when user paste something inside it or change, by any way, the input content.

我希望当用户在其中粘贴某些内容或以任何方式更改输入内容时触发我的输入。

p.s: my method works as expected, the only thing that doesn't work is...this.

ps:我的方法按预期工作,唯一不起作用的是......这个。

回答by Shhade Slman

Use can use keydown Event

使用可以使用 keydown 事件

input.on('keydown ', function(event){
    console.log("Code: " + event.which);
});

回答by dan richardson

I think it's because your event isn't correct, you're matching an "input" event for the input.
This might be what you're after (notice the pasteevent):

我认为这是因为您的事件不正确,您正在为输入匹配“输入”事件。
这可能是您所追求的(注意paste事件):

jQuery(function () {
  jQuery("#post-input").on('keyup', function(event){
    if(!(event.ctrlKey || $(this).data('skipkeyup'))) {
        console.log('keyup', event);
    } else {
        $(this).data('skipkeyup', true)
    }
  }).on('paste', function (event) {
      console.log('paste event', event);
  }).on('keydown', function(){
      $(this).data('skipkeyup', false)
  })

});

});

http://jsfiddle.net/uBZF9/9/

http://jsfiddle.net/uBZF9/9/

回答by FreshPro

Check this Fiddle

检查这个小提琴

I'm not sure is that what you want but here you go

我不确定那是你想要的,但你去吧

input.on('keyup keydown copy', function(event){
    console.log("Code: " + event.keyCode);
    console.log("Code: " + event.which);
    console.log("Code: " + window.event ? event.keyCode : event.which);
});