Javascript 用户在文本框中按 Enter 的 JQuery 事件?

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

JQuery Event for user pressing enter in a textbox?

javascriptjqueryjquery-events

提问by Click Upvote

Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?

Jquery 中是否有任何事件仅在用户点击文本框中的输入按钮时触发?或者可以添加任何插件来包含这个?如果没有,我将如何编写一个快速插件来做到这一点?

回答by Jishnu A P

You can wire up your own custom event

您可以连接自己的自定义事件

$('textarea').bind("enterKey",function(e){
   //do stuff here
});
$('textarea').keyup(function(e){
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

http://jsfiddle.net/x7HVQ/

http://jsfiddle.net/x7HVQ/

回答by Etienne Dupuis

   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

回答by Naftali aka Neal

Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)

这是一个给你的插件:(小提琴:http: //jsfiddle.net/maniator/CjrJ7/

$.fn.pressEnter = function(fn) {  

    return this.each(function() {  
        $(this).bind('enterPress', fn);
        $(this).keyup(function(e){
            if(e.keyCode == 13)
            {
              $(this).trigger("enterPress");
            }
        })
    });  
 }; 

//use it:
$('textarea').pressEnter(function(){alert('here')})

回答by jzilla

heres a jquery plugin to do that

这是一个 jquery 插件来做到这一点

(function($) {
    $.fn.onEnter = function(func) {
        this.bind('keypress', function(e) {
            if (e.keyCode == 13) func.apply(this, [e]);    
        });               
        return this; 
     };
})(jQuery);

to use it, include the code and set it up like this:

要使用它,请包含代码并像这样设置它:

$( function () {
    console.log($("input"));
    $("input").onEnter( function() {
        $(this).val("Enter key pressed");                
    });
});

jsfiddle of it here http://jsfiddle.net/VrwgP/30/

jsfiddle在这里http://jsfiddle.net/VrwgP/30/

回答by Joshua Burns

It should be well notedthat the use of live()in jQuery has been deprecatedsince version 1.7and has been removedin jQuery 1.9. Instead, the use of on()is recommended.

应该很好注意的是,使用live()jQuery中已经过时,因为版本1.7和已删除的jQuery的1.9。相反,on()建议使用 。

I would highly suggest the following methodology for binding, as it solves the following potential challenges:

我强烈建议使用以下绑定方法,因为它解决了以下潜在挑战:

  1. By binding the event onto document.bodyand passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.bodyrather than $selectordirectly, which means $selectorcan be added, removed and added again and will never load the event bound to it.
  2. By calling off()before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
  3. By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready()does not get fired for AJAX requests, while $(function() {...})does.
  1. 通过将事件绑定到document.body并将 $selector 作为第二个参数传递给on(),元素可以从 DOM 附加、分离、添加或删除,而无需处理重新绑定或双重绑定事件。这是因为事件是附加到document.body而不是$selector直接附加的,这意味着$selector可以添加、删除和再次添加,并且永远不会加载绑定到它的事件。
  2. 通过调用off()before on(),这个脚本可以存在于页面的主体中,也可以存在于 AJAX 调用的主体中,而不必担心意外的双重绑定事件。
  3. 通过将脚本包装在 中$(function() {...}),该脚本可以再次由页面主体或 AJAX 调用的主体加载。$(document).ready()不会因 AJAX 请求而被触发,而$(function() {...})会。

Here is an example:

下面是一个例子:

<!DOCTYPE html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var $selector = $('textarea');

        // Prevent double-binding
        // (only a potential issue if script is loaded through AJAX)
        $(document.body).off('keyup', $selector);

        // Bind to keyup events on the $selector.
        $(document.body).on('keyup', $selector, function(event) {
          if(event.keyCode == 13) { // 13 = Enter Key
            alert('enter key pressed.');
          }
        });
      });
    </script>
  </head>
  <body>

  </body>
</html>

回答by Phan Van Linh

If your input is search, you also can use on 'search'event. Example

如果您的输入是search,您也可以使用on 'search'事件。例子

<input type="search" placeholder="Search" id="searchTextBox">

.

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

回答by yogesh lodha

HTML Code:-

HTML代码:-

<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />      

<input type="button" id="btnclick">

Java Script Code

Java 脚本代码

function AddKeyPress(e) { 
        // look for window.event in case event isn't passed in
        e = e || window.event;
        if (e.keyCode == 13) {
            document.getElementById('btnEmail').click();
            return false;
        }
        return true;
    }

Your Form do not have Default Submit Button

您的表单没有默认提交按钮

回答by Wilco

Another subtle variation. I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:

另一个微妙的变化。我进行了轻微的权力分离,所以我有一个插件来启用捕获回车键,然后我只是正常绑定到事件:

(function($) { $.fn.catchEnter = function(sel) {  
    return this.each(function() { 
        $(this).on('keyup',sel,function(e){
            if(e.keyCode == 13)
              $(this).trigger("enterkey");
        })
    });  
};
})(jQuery);

And then in use:

然后在使用中:

$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });

This variation allows you to use event delegation (to bind to elements you haven't created yet).

此变体允许您使用事件委托(绑定到您尚未创建的元素)。

$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });

回答by Arne M

I could not get the keypressevent to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:

keypress在我阅读了 jQuery 文档之前,我无法为输入按钮触发事件,并且挠了一段时间:

"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)

" keypress 事件在浏览器注册键盘输入时发送到一个元素。这与 keydown 事件类似,除了修饰符和非打印键,如 Shift、Esc 和 delete 触发 keydown 事件,但不触发 keypress 事件。" ( https://api.jquery.com/keypress/)

I had to use the keyupor keydownevent to catch a press of the enter button.

我不得不使用keyuporkeydown事件来捕捉按下回车按钮。