jquery - 将焦点移到另一个 div 中的下一个输入
问题描述
我有以下代码:
<div class="postcode">
<div>
<input type="text" maxlength="4">
</div>
<div>
<input type="text" maxlength="4">
</div>
</div>
一旦输入了 4 个字符,我需要 Jquery 自动关注下一个输入。我尝试了以下方法,但这仅在输入彼此相邻时才有效:
$(".postcode input").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.postcode input').focus();
}
});
这也意味着当我 shift+tab 时,它会一直关注下一个 div。
最后,如果用户从第二个输入中删除所有字符,我还需要它返回到第一个输入。
解决方案
移动到下一个输入
使用parent()
选择 parent <div>
,移动到next()
DIV 和find()
child input 以专注于它。请注意,您应该添加:first
以便在第一个input
.
$(".postcode input:first").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).parent().next().find('input').focus();
}
});
Shift+Tab 保持焦点
添加focus
事件以触发相同输入的keyup
事件以再次聚焦第二个输入。
$(".postcode input:first").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).parent().next().find('input').focus();
}
}).focus(function(){
$(this).trigger('keyup');
});
推荐阅读
- sql - 检查列是否有空值
- sql - <-> 运算符的文档/定义?
- java - 无法解析方法“putExtra(java.lang.String,com.example.talkmore.models.User)”
- git - 如何使用正确的 Git Diff 创建三级功能分支
- stylelint - Stylelint - 使 CSS 在子类定义之前出现
- amazon-s3 - 增量表中的查询
- snowflake-cloud-data-platform - 雪花错误:SQL 访问控制错误:权限不足,无法操作帐户'
' - scala - 如何在Scala的for循环中跳过迭代?
- python - 如果使用 JSON 字段,则选择太长
- powershell - 如果条件不匹配,则使用 powershell 重试命令