Jquery中是否有任何事件只在用户点击文本框中的回车按钮时才会触发?或者任何插件,可以添加到包括这个?如果不是,我该如何编写一个快速插件来做到这一点?


当前回答

另一个微妙的变化。 我采取了轻微的权力分离,所以我有一个插件来捕捉enter键,然后我只是正常地绑定到事件:

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

然后在使用中:

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

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

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

其他回答

这里有一个插件给你:(小提琴: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')})
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
   <input type="text" name="search" id="search">
</form>
<script>
   function doSomething(event){
      let $val = $('form#searchForm input[name="search"]').val();
        console.log($val);
      event.preventDefault();
    }
</script>
 One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.

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

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

.

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

//简单明了的解决方案

$(document).ready(function(){

$('#TextboxId').keydown(function(event){
    if (event.which == 13){
       //body or action to be performed
    }
});

});

另一个微妙的变化。 我采取了轻微的权力分离,所以我有一个插件来捕捉enter键,然后我只是正常地绑定到事件:

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

然后在使用中:

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

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

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