Javascript 事件监听器回车键

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

EventListener Enter Key

javascript

提问by Jeremy

Is there an addEventListenerfor the Enterkey?

是否有addEventListenerEnter关键?

I have

我有

document.querySelector('#txtSearch').addEventListener('click', search_merchants);

I know this is intended for <button>, but wanted to know if there's an equivalent for catching the Enterkey.

我知道这是为了<button>,但想知道是否有等效的捕捉Enter钥匙。

回答by Trevor

Are you trying to submit a form?

您是否正在尝试提交表单?

Listen to the submitevent instead.

submit改为监听事件。

This will handle clickand enter.

这将处理clickenter

If you must use enter key...

如果必须使用回车键...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

回答by Marcus

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

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

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

回答by Richard Schneider

You could listen to the 'keydown'event and then check for an enter key.

您可以收听该'keydown'事件,然后检查是否有回车键。

Your handler would be like:

你的处理程序是这样的:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}