javascript - 当没有兄弟时,用 jquery 查找下一个

标签 javascript jquery

在输入中输入 maxlength 个字符后,我需要关注下一个输入。问题是下一个输入并不总是同级:

jQuery("input").on('input', function() {
  if (jQuery(this).val().length == jQuery(this).attr('maxlength')) {
    jQuery(this).next("input").focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When you have write 4 char, the focus have to switch to the next input:
<div>
  OK
  <input maxlength="4">
  <input maxlength="4">
</div>
KO
<input id="inputWithTheIssue">

最佳答案

您不能使用.next() 函数,因为所有输入 都不是同级。因此,您需要在整个输入控件集中找到当前输入的索引,并将其加1以找到下一个出现的输入元素。

jQuery("input").on('input',function () {
            if(jQuery(this).val().length == jQuery(this).attr('maxlength')) {
              var currIndex = $(this).index();  // gets the index value w.r.t the other input controls
              $('input').eq(currIndex + 1).focus();
            }
        });

工作示例:https://jsfiddle.net/DinoMyte/uhpn7pyx/2/

关于javascript - 当没有兄弟时,用 jquery 查找下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35754545/

相关文章:

javascript - 用户使用 Electron 输入 JavaScript - Window.Prompt() 的替代方案

javascript - 如何将下拉菜单从垂直线对齐到水平线?

javascript - DataTable分页后无法点击按钮

javascript - 无需询问您的位置即可确定用户所在的县

javascript - datetimepicker 无法与 bootstrap 4 一起使用?

javascript - 将单击事件绑定(bind)到容器,但从事件逻辑中排除容器内的元素

jquery - 使用 JQuery-File-Upload 和 Paperclip 时出现多个文件上传错误

javascript - 选择其他选项卡时禁用默认选项卡

jQuery如何循环函数

javascript - Jquery Mobile - 单击弹出窗口(标题和内容的任何区域)自动聚焦文本字段