Jquery keyup then next()

Jquery keyup then next()

本文关键字:next then keyup Jquery      更新时间:2023-09-26

我有一个表格,它被分成单独的输入框,访问者将字母输入到一个完整的单词中。每个输入的最大长度属性为 1,由 keyup() 捕获,如果输入长度等于 1,则使用 next() 进入下一个输入。

这个系统工作正常,人们抱怨当他们快速打字时会错过字母。我很想知道这是否只是无法克服的next()函数延迟,或者这只是我的编码错误?

这是一个JSFiddle,下面是一个可运行的堆栈片段:

$('#psw input').keyup(function(e) {
  if ($(this).val().length > 1) {
    $(this).val($(this).val().substring(0, 1));
  }
  if ($(this).val().length == $(this).attr("maxlength")) {
    if ($(this).next('[type="text"]').length > 0) {
      $(this).next('[type="text"]')[0].focus();
    }
  }
});
$('#psw input').keydown(function(e) {
  if ((e.which == 8 || e.which == 46) && $(this).val() == '') {
    if ($(this).prev('[type="text"]').length > 0) {
      $(this).prev('[type="text"]')[0].focus();
    }
  }
});
input {
  width: 30px;
  height: 30px;
  margin: 20px;
  text-align: center;
  font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="psw">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
</div>

问题是快速键入的用户通常会同时按下多个键,因此当您依赖 keyup 时,您会得到不一致的结果,因为当用户在释放第一个键时,他们已经按下了第二个键。

下面是函数的修改版本,仅使用 keydown,以及setTimeout,以便在用户按退格键时删除当前字段中的字符,然后再跳转到上一个字段。这是有效的setTimeout因为在浏览器执行队列中执行用户的退格键后,会将字段移动命令排队。不需要密钥缓冲区或任何其他复杂的东西。

这消除了按键很快被按下的所有问题。快速打字时尝试一下!

现场演示:

$('#psw input').keydown(function(e) {
  if ((e.which == 8 || e.which == 46)) {
    if ($(this).prev('[type="text"]').length > 0) {
      var self = this;
      setTimeout(function() {
        $(self).prev('[type="text"]')[0].focus();
      }, 0);
    }
    return;
  }
  if ($(this).val().length > 1) {
    $(this).val($(this).val().substring(0, 1));
  }
  if ($(this).val().length == $(this).attr("maxlength")) {
    if ($(this).next('[type="text"]').length > 0) {
      $(this).next('[type="text"]')[0].focus();
    }
  }
});
input {
  width: 30px;
  height: 30px;
  margin: 20px;
  text-align: center;
  font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="psw">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
  <input type="text" maxlength="1">
</div>

JSFiddle 版本: https://jsfiddle.net/873f4Lo0/2/