简体   繁体   English

当用户按下进入时的JQuery事件?

[英]JQuery Event for when user presses enter?

在文本框中输入后,只要用户点击进入,就会调用函数的最简单方法是什么?

You'll need to listen for the keypress event. 你需要听一下keypress事件。 It's probably easiest to do this with delegate : 使用delegate执行此操作可能最简单:

$(document.body).delegate('input:text', 'keypress', function(e) {
    if (e.which === 13) { // if is enter
        e.preventDefault(); // don't submit form

        // do what you want here
    }
});
<textarea id="text"></textarea>

$('#text').keydown(function(e){
    if (e.keyCode == 13) {
        alert('Enter was pressed.');
    }
});

http://jsfiddle.net/dNfC2/ http://jsfiddle.net/dNfC2/

HTML code HTML代码

<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>

jquery code jquery代码

$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});

Running example here : http://jsfiddle.net/Xamkp/5/ 在这里运行示例: http//jsfiddle.net/Xamkp/5/

try this: 尝试这个:

jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });

you will need a plugin: jquery.hotkeys 你需要一个插件: jquery.hotkeys

Well it's rather simple to do in the form you asked: 嗯,你问的形式很简单:

$('#idOfTextBox').keyup(function(event){
     // enter key pressed
     if(event.keyCode=='13')yourFunction();
});

Take note this will still append the enter key to the box. 请注意,这仍然会将回车键附加到框中。 You might wanna try keydown or keypressed if you don't want that. 如果你不想那样,你可能想尝试keydownkeypressed

Be sure to check keyUp() for more detail. 请务必查看keyUp()以获取更多详细信息。

Put the <input> in a form, and write a handler for the form's submit event. <input>放在表单中,并为表单的submit事件编写处理程序。

This way you're not explicitly looking for any particular key; 这样你就不会明确地寻找任何特定的键; you're just waiting for the form to be submitted normally. 你只是在等待表格正常提交。 And in every mainstream browser, pressing enter while filling out a form will submit the form. 在每个主流浏览器中,在填写表单时按Enter键将提交表单。

Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form). 请注意,您不需要有物理提交屏幕上的按钮,如果你不想(在这种情况下回车键将可能提交表单的唯一途径)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM