这是我一直在研究的 jsfiddle 示例:
http://jsfiddle.net/4m5fg/143/
HTML:
<input type="text" maxlength="1" size="1"/>
<input type="text" maxlength="1" value="e" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1"/>
<input type="text" maxlength="1" value="r" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1"/>
JS:
$("input").bind("input", function() {
var $this = $(this);
setTimeout(function() {
if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
$this.next("input").focus();
},0);
});
在上面的示例中,如果我从最左边的文本框开始,如何才能使在该文本框中输入字符时光标前进到下一个空白文本框(而不是下一个填充的文本框)-- -并以这种方式继续其他文本框。
最佳答案
这应该可以解决问题:
$("input").on("input", function () {
var $this = $(this);
if ($this.val().length >= parseInt($this.attr("maxlength"), 10)) {
var nextEmpty = $this.nextAll("input[value=''], input:not([value])")[0];
if (nextEmpty) {
nextEmpty.focus();
}
}
});
它将找到第一个具有空值属性或根本没有值属性的input
同级。如果找到这样的 sibling ,它将获得焦点。
http://jsfiddle.net/4m5fg/149/
请注意,我删除了 setTimeout 函数,因为它在超时为 0 时似乎没有用...
关于javascript - 自动跳到下一个空白文本输入框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25704462/