如何使用 Enter 键作为事件处理程序 (javascript)?

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

How do I use the Enter key as an event handler (javascript)?

javascripteventsbuttonhandlerenter

提问by Juan Veliz

im trying to make my own chat... so i have an input text field, the submit button, isn't even submit, its just a button.... so when the enter key is pressed, i need the value of the input field to appear in my textarea (which is readonly)...

我正在尝试进行自己的聊天......所以我有一个输入文本字段,提交按钮,甚至没有提交,它只是一个按钮......所以当按下回车键时,我需要的值输入字段出现在我的文本区域(只读)...

well look.. make long story short, i just want a basic enter key event handler, i know it works perfectly with submit buttons cus you don't need to program anything at all, its default. but my button is type="button" .... so when you press enter nothing happens... how do i trigger my button by pressing enter?

好吧,长话短说,我只想要一个基本的输入键事件处理程序,我知道它与提交按钮完美配合,因为你根本不需要编程任何东西,它的默认值。但我的按钮是 type="button" .... 所以当你按下 enter 时什么也没有发生......我如何通过按下 enter 来触发我的按钮?

回答by entonio

You could make the button type submit, or you can use the onkeyupevent handler and check for keycode 13.

您可以使按钮 type submit,或者您可以使用onkeyup事件处理程序并检查键码 13。

Here's a list of key codes: Javascript Char codes/Key codes). You'll have to know how to get the keycode from the event.

这是键代码列表:Javascript 字符代码/键代码)。您必须知道如何从事件中获取键码。

edit: an example

编辑:一个例子

HTML:

HTML:

<input onkeyup="inputKeyUp(event)" ...>

Plain javascript:

普通的javascript:

function inputKeyUp(e) {
    e.which = e.which || e.keyCode;
    if(e.which == 13) {
        // submit
    }
}

回答by samccone

Here is a working code snippet for listening for the enter key

这是一个用于监听回车键的工作代码片段

$(document).ready(function(){

    $(document).bind('keypress',pressed);
});

function pressed(e)
{
    if(e.keyCode === 13)
    {
        alert('enter pressed');
        //put button.click() here
    }
}

回答by Marcus

Here is a version of the currently accepted answer (from @entonio) with keyinstead of keyCode:

这是当前接受的答案(来自@entonio)的一个版本,其中包含key而不是 keyCode:

HTML:

HTML:

<input onkeyup="inputKeyUp(event)" ...>

Plain javascript:

普通的javascript:

function inputKeyUp(e) {
    if (e.key === 'Enter') {
        // submit
    }
}