我已经从本次讨论中更改了代码,以致于如果我按Enter键,它将进入第一个按钮,如果我按Tab键,它将进入第二个按钮。但是现在我的问题是,从第一个按钮开始,如果我按Enter键,则不会调用该按钮;如果再次从第二个按钮中按下Tab,则不会转到第一个按钮。所以我需要这些事情发生:
1)如果我按回车键,则从第一个/第二个按钮调用(单击)
2)如果我从第二个按钮中单击选项卡,则它应该在第一和第二之间。
这是我使用的代码。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hel">hello</button>
<button id="hel1" >hello1</button>
<script>
$(function() {
$(document).keydown(function(e) {
if (e.keyCode == 13) {
$("button#hel").focus();
}
if (e.keyCode == 9) {
$("button#hel1").focus();
}
return false;
});
});
</script>
我应该做些什么改变?
亚历克西斯(Alexis)已经很近了,但是您希望焦点在第一次输入后移到该按钮上,因此您要做的是设置一个检测器。您还希望它在按Tab时在按钮之间循环,如果在prss标签上时它们位于最后一个按钮,则返回顶部。如果某个按钮已聚焦,则单击该按钮(如果没有),则转到第一个按钮。
试试这个:
$(function() {
$(document).keydown(function(e) {
var currentBtn = $(".mybtn:focus"),
inputs = $(".mybtn"),
currentIndex = inputs.index(currentBtn),
next = inputs.filter(function (index) {
if (currentIndex < inputs.length) {
return index == currentIndex + 1;
} else {
return index == 0;
}
});
if (e.keyCode == 13) {
if (currentBtn.length) {
currentBtn.click();
} else {
$(".mybtn").first().focus();
}
}
if (e.keyCode == 9) {
if (currentBtn.length) {
if (currentBtn.is(".mybtn:last")) {
$(".mybtn").first().focus();
} else {
next.focus();
}
} else {
$(".mybtn").first().focus();
}
}
return false;
});
});
$("button#hel").on('click', function(){
alert("hello press");
});
$("button#hel1").on('click', function(){
alert("hello1 press");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hel" class='mybtn'>hello</button>
<button id="hel1" class='mybtn' >hello1</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句