如何使用 Enter 键作为事件处理程序 (javascript)?
我试图进行自己的聊天...所以我有一个输入文本字段,提交按钮,甚至不是提交,它只是一个按钮...所以当按下回车键时,我需要的值输入字段出现在我的文本区域(只读)中......
好吧......长话短说,我只想要一个基本的输入键事件处理程序,我知道它与提交按钮完美配合,因为你不需要编程任何东西,它的默认值。但我的按钮是 type="button" ....所以当你按 Enter 时什么也没有发生...我如何通过按 Enter 触发我的按钮?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使按钮类型为
submit
,也可以使用onkeyup
事件处理程序并检查键码 13。以下是键码列表:Javascript 字符代码/键代码) 。您必须知道如何从事件中获取键码。
编辑:示例
HTML:
纯 JavaScript:
You could make the button type
submit
, or you can use theonkeyup
event handler and check for keycode 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.
edit: an example
HTML:
Plain javascript:
这是一个用于监听回车键的工作代码片段
Here is a working code snippet for listening for the enter key
这是当前接受的答案的一个版本(来自@entonio),其中 key 而不是 keyCode:
HTML:
纯 JavaScript:
Here is a version of the currently accepted answer (from @entonio) with key instead of keyCode:
HTML:
Plain javascript: