在keydown事件之后关注字段而不插入字符

Par*_*n0a 5 javascript jquery

我有一个快捷键K.它应该专注于我的输入,但我不希望它K在焦点时插入字母.

$(document).keydown(function(event) { 
    if (event.which == 75) {
        $('input').focus();
    }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 4

您可以用来event.preventDefault()停止事件的标准行为。但请注意,这将阻止该字母Kinput. keydown为了允许您需要向其自身添加一个处理程序input,以阻止事件传播到达document. 尝试这个:

$(document).keydown(function(event) {
  if (event.which == 75) {
    event.preventDefault();
    $('input').focus();
  }
});

$('input').keydown(function(e) {
  e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">
Run Code Online (Sandbox Code Playgroud)