Jquery keyup then next()
Jquery keyup then next()
我有一个表格,它被分成单独的输入框,访问者将字母输入到一个完整的单词中。每个输入的最大长度属性为 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/
相关文章:
- Javascript:If-then语句在函数中不起作用
- angularjs无法读取未定义的属性then
- ES6生成器:.next()的输入值
- 使用next、prev按钮制作简单的jQuery图像滑块
- Promise函数在.then之后未运行函数化
- Redux中间件在next()之前更改状态
- 为什么$.when().pipe().then()有效,而$.when
- 如何在异步函数中正确使用Promise.all()和then()
- $resource上带有.then()函数的角度自定义方法导致错误
- 可以链接 '.then() 的返回响应,顺序与 '.then()' 的顺序不同
- AngularJS因果报应测试规范承诺未解析,且未调用.then()
- 在javascript promise中正确使用then
- 将数据从promise then方法传递到对象方法
- Angular Provider/JS-如何访问'叔叔方法'从$http().then()
- 当链接javascript承诺时,如何处理then()函数中的条件
- 如何禁用FuelUX向导步骤1中的NEXT按钮
- 如何在ES Next中扩展静态属性
- JavaScript Promise then() ordering
- Jquery keyup then next()
- 承诺链接:在next-then回调中使用上一个承诺的结果