我正在尝试使用jQuery UI :tabbable
选择器来选择页面上的下一个和上一个输入元素。我有以下HTML
<div id="section1">1.
<input type="text" />2.
<input type="text" />
</div>
<div id="section2">3.
<input type="text" />4.
<input type="text" />5.
<input type="text" />
</div>
Run Code Online (Sandbox Code Playgroud)
和以下javascript
$(document).ready(function () {
$("input").on("keyup", function (event) {
if (event.keyCode == 40) $(this).next(":tabbable").focus();
else if (event.keyCode == 38) $(this).prev(":tabbable").focus();
});
});
Run Code Online (Sandbox Code Playgroud)
选择器似乎在div中工作正常。例如,如果我在输入3中并按下,它将进入输入4。但是,如果我按下选择器,则找不到输入2。
您可以使用.index()
输入元素中的来在它们之间切换。
$("input").on("keyup", function (event) {
if (event.keyCode == 40) {
$('input').eq(parseInt($('input').index($(this)), 10) + 1).focus();
} else if (event.keyCode == 38) {
$('input').eq(parseInt($('input').index($(this)), 10) - 1).focus();
}
});
Run Code Online (Sandbox Code Playgroud)