javascript - 自动制表符不适用于中间的文本?

标签 javascript jquery html

标题表明,自动制表符不适用于两个文本框之间的文本。

基本上,当两个文本框之间存在跨度时,它不会在两个文本框之间切换。

这是不起作用的:

HTML

<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>

JavaScript

$(".fill-out").keyup(function () {
    debugger
        if (this.value.length == this.maxLength) {
          $(this).next('.fill-out').focus();
        }
  });

正如我上面所说,它不起作用,但是,如果我删除两个跨度,一切都会正常工作。

JavaScript 保持不变,我只删除了两个跨度:

HTML

<input class="fill-out" type="text" maxlength="1"/>
<input class="fill-out" type="text" maxlength="1"/>
<input class="fill-out" type="text" maxlength="1"/>

JavaScript

$(".fill-out").keyup(function () {
    debugger
        if (this.value.length == this.maxLength) {
          $(this).next('.fill-out').focus();
        }
  });

谁能解释一下为什么,或者是否有其他方法可以做到这一点?

最佳答案

在 jQuery 中,next()将找到紧随其后的元素。使用选择器意味着它只会返回紧随其后的元素如果该元素与您的选择器匹配。

您应该使用nextAll()相反,它将找到所有适合选择器的项目...然后使用 first()使用第一个。

$(".fill-out").keyup(function () {
  if (this.value.length == this.maxLength) {
    $(this).nextAll('.fill-out').first().focus();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>

或者,您也可以使用 CSS 伪类 :first而不是 first()...

$(this).nextAll('.fill-out:first').focus();
<小时/>

确实,这应该是一个新问题,但根据OP的评论......

Is there a way for it to deselect the text box if there's none to go-to anymore?

要在输入最后一项后“取消选择”光标,您可以执行以下操作,在其中存储“下一项”,如果不存在,则blur() 当前一项.

$(".fill-out").keyup(function () {
  if (this.value.length == this.maxLength) {
    var $next = $(this).nextAll('.fill-out').first().focus();
    if ($next.length == 0) {
      $(this).blur();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>
<span class="text">x</span>
<input class="fill-out" type="text" maxlength="1"/>

您不需要创建 var $next 但我认为它比下面直接获取 .length 更容易阅读...

if ($(this).nextAll('.fill-out').first().focus().length == 0) {
  $(this).blur();
}

关于javascript - 自动制表符不适用于中间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313097/

相关文章:

jquery - 您能否使一段 HTML 仅受一个样式表影响?

html - Flex 盒子布局,调整 block 的高度

jquery - 在 Bootstrap Carousel 中嵌入 Google map

javascript - jquery 选择器获取给定 div 内的所有 anchor 元素,无论它们嵌套多深?

php - 从 php 调用参数化的 javascript 函数

javascript - 在加载的 JS 文件中使用 django 模板逻辑(集成 django JS)

javascript - jquery/js 错误 - DOM 错误 : DOM Exception 8 - When I . html 任何变量

html - Highcharts Pie 自定义图例,可能吗?

javascript - 在 div 内滚动时使用 jQuery 添加/删除类

javascript - 我应该如何将 OOP 模式实现到交互式 Web 应用程序(借助 jQuery)?