如何获取输入元素上的关键TAB事件? [英] How to get the key TAB event on an input element?

查看:92
本文介绍了如何获取输入元素上的关键TAB事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在输入字段中按下返回键时,我尝试触发一个按钮.这行得通.但是,如果我按Tab键,则不会触发任何事情,因为没有捕获TAB键事件.

I try to trigger a button when in an input field the return key has been hit. This works. But if I hit the tab key nothing is triggered because the TAB key event isn't captured.

小提琴示例

例如,这是我的JQ代码段:

Here is my JQ code snippet for example:

$("input[name=input]").on("keypress, keydown, keyup", function(e) {
  var code = e.keyCode || e.which;
  if ( code == 13 || code == 9 ) {
    $("input[name=btn]").trigger("click");
  }
});

我不知道如何使Tab键像返回键一样工作.

I can't figure out how to get the tab key stroke working like a return key stroke.

推荐答案

  • 使用Event.preventDefault()可以防止浏览器将焦点切换到 Tab 上.
  • 仅收听"keydown"事件
  • 改为使用 KeyboardEvent.key
    • Use Event.preventDefault() to prevent the browser switching focus on Tab press.
    • Listen for "keydown" event only
    • Use KeyboardEvent.key instead
    • JavaScript的 which和keyCode已弃用,从历史上看,它们都变得一团糟.
      即使jQuery对Event.keyCodeEvent.which跨浏览器都使用jQueryEvent.which进行了标准化,我认为我们也应该放弃两者,并使用更人性化的 Event.key . 9'Tab'哪个更有意义? 13'Enter'? 42或...反正是42

      JavaScript's which and keyCode are deprecated, historically they both become a mess.
      Even if jQuery normalizes with jQueryEvent.which for both Event.keyCode and Event.which crossbrowser, I think we should abandon the two and use the more human friendly Event.key. What makes more sense, 9 or 'Tab'? 13 or 'Enter'? 42 or... what is 42 anyways

      $('input[name=input]').on('keydown', function(evt) {
        if (evt.key === 'Tab' || evt.key === 'Enter') {
          evt.preventDefault();
          $('input[name=btn]').trigger('click');
        }
      });
      

      这篇关于如何获取输入元素上的关键TAB事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆