标题表明,自动制表符不适用于两个文本框之间的文本。
基本上,当两个文本框之间存在跨度时,它不会在两个文本框之间切换。
这是不起作用的:
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/