我尝试制作像测验一样的填字游戏,并且当输入是带有字母的字段时需要更改输入焦点。问题是我可以将焦点更改为同一 div 中的字段
$(".inputs").keyup(function () {
$(this).next().focus();
});
或者两个div之间
$(':input').keyup(function (e) {
if ($(this).val().length == $(this).attr('maxlength')) {
$(this).closest('div').next().find(':input').first().focus();
}
})
但我不知道如何改变对下一个输入的焦点,不管它是在同一个 div 中还是在另一个 div 中。
<div class="answer_1">
<input class="inputs letter square border_orange" maxlength="1" type="text" />
<input class="inputs letter square border_orange" maxlength="1" type="text" />
</div>
<div class="answer_2">
<input class="inputs letter square border_orange" maxlength="1" type="text" />
<input class="inputs letter square border_orange" maxlength="1" type="text" />
</div>
Html 代码在上面,我尝试首先在answer_1 div 中的输入中更改输入焦点,当我完成此处的第二个输入时,自动将焦点更改为下一个 div 中的输入。 有什么建议吗?
最佳答案
您可以使用输入集合,并使用单击元素的索引遍历它:
var $inputs = $(".inputs"); // get the collection of inputs
$inputs.keyup(function () {
var index = $inputs.index(this); // get the index of the current input
$inputs.eq(index + 1).focus(); // focus the next input
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answer_1">
<input class="inputs letter square border_orange" maxlength="1" type="text" />
<input class="inputs letter square border_orange" maxlength="1" type="text" />
</div>
<div class="answer_2">
<input class="inputs letter square border_orange" maxlength="1" type="text" />
<input class="inputs letter square border_orange" maxlength="1" type="text" />
</div>
关于javascript - 输入焦点变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297580/