欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何使用jQuery检测按键盘输入?

程序员文章站 2022-05-27 10:33:46
...

本文翻译自:How to detect pressing Enter on keyboard using jQuery?

I would like to detect whether the user has pressed Enter using jQuery. 我想检测用户是否使用jQuery按Enter键

How is this possible? 这怎么可能? Does it require a plugin? 它需要插件吗?

EDIT: It looks like I need to use the keypress() method. 编辑:看起来我需要使用keypress()方法。

I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about? 我想知道是否有人知道该命令是否存在浏览器问题 - 比如我是否应该了解任何浏览器兼容性问题?


#1楼

参考:https://stackoom.com/question/46r0/如何使用jQuery检测按键盘输入


#2楼

The easy way to detect whether the user has pressed enter is to use key number the enter key number is =13 to check the value of key in your device 检测用户是否按下输入的简单方法是使用**编号输入**编号= 13来检查设备中**的值

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // backspace in IE only be on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

by pressing the enter key you will get result as 13 . 按回车键,结果为13。 using the key value you can call a function or do whatever you wish 使用键值可以调用函数或执行任何操作

        $(document).keypress(function(e) {
      if(e.which == 13) {
console.log("User entered Enter key");
          // the code you want to run 
      }
    });

if you want to target a button once enter key is pressed you can use the code 如果您想在按下回车键后按下按钮,则可以使用该代码

    $(document).bind('keypress', function(e){
  if(e.which === 13) { // return
     $('#butonname').trigger('click');
  }
});

Hope it help 希望它有所帮助


#3楼

You can do this using the jquery 'keydown' event handle 您可以使用jquery'keydown'事件句柄来完成此操作

   $( "#start" ).on( "keydown", function(event) {
      if(event.which == 13) 
         alert("Entered!");
    });

#4楼

In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field. 在某些情况下,您可能需要禁止页面的某个区域的ENTER键,而不是页面的其他区域,如下面的页面包含带有SEARCH字段的标题 <div>

It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community. 我花了一些时间来弄清楚如何做到这一点,我在这里为社区发布这个简单而完整的例子。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Test Script</title>
  <script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $('.container .content input').keypress(function (event) {
      if (event.keyCode == 10 || event.keyCode == 13) {
        alert('Form Submission needs to occur using the Submit button.');
        event.preventDefault();
      }
    });
  </script>
</head>
  <body>
    <div class="container">
      <div class="header">
        <div class="FileSearch">
          <!-- Other HTML here -->
        </div>
      </div>
      <div class="content">
        <form id="testInput" action="#" method="post">
        <input type="text" name="text1" />
        <input type="text" name="text2" />
        <input type="text" name="text3" />
        <input type="submit" name="Submit" value="Submit" />
        </form>
      </div>
    </div>
  </body>
</html>

Link to JSFiddle Playground : The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form. 链接到JSFiddle Playground[Submit]按钮不执行任何操作,但是从其中一个Text Box控件按Enter键将不会提交表单。


#5楼

I spent sometime coming up with this solution i hope it helps someone. 我花了一些时间来提出这个解决方案,我希望它可以帮助某人。

$(document).ready(function(){

  $('#loginforms').keypress(function(e) {
    if (e.which == 13) {
    //e.preventDefault();
    alert('login pressed');
    }
  });

 $('#signupforms').keypress(function(e) {
    if (e.which == 13) {
      //e.preventDefault();
      alert('register');
    }
  });

});

#6楼

A minor extension of Andrea's answer above makes the helper method more useful when you may also want to capture modified enter presses (ie ctrl-enter or shift-enter). Andrea上面的答案的一个小扩展使得辅助方法更有用,当您可能还想捕获修改后的输入按下(即ctrl-enter或shift-enter)。 For example, this variant allows binding like: 例如,此变体允许绑定,如:

$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')

to submit a form when the user presses ctrl-enter with focus on that form's textarea. 当用户按下ctrl-enter时,提交一个表单,焦点在该表单的textarea上。

$.fn.enterKey = function (fnc, mod) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
                fnc.call(this, ev);
            }
        })
    })
}

(see also Ctrl+Enter jQuery in TEXTAREA ) (另请参阅Ctrl +在TEXTAREA中输入jQuery