输入按钮的键

Enter key for button

我已经根据 讨论更改了我的代码,如果我按回车键它会转到第一个按钮,如果我按 Tab 键它会转到第二个按钮。但现在我的问题是,从第一个按钮开始,如果我按下 enter,它不会调用该按钮,如果我再次从第二个按钮按下 tab,它不会转到第一个按钮。 所以我需要这些事情发生:

1) 从 first/second 按钮,如果我按下回车,按钮应该调用(点击)

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>

我应该做出什么改变?

你可以尝试这样的事情。

它有效,但也许有更好的方法。

$(function() {
$(document).keydown(function(e) {
if (e.keyCode == 13) {
      $(".mybtn").is(":focus").trigger("click");
}
if (e.keyCode == 9) {
    if($("button#hel").is(":focus"))
    $("button#hel1").focus();
  else
    $("button#hel").focus();
}
return false;
});

$("button#hel").focus();
});

$("button#hel").click(function(){
  alert("hello press");
  });

$("button#hel1").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>

Alexis 很接近,但您希望焦点在第一次输入后转到按钮,所以您要做的是设置一个检测器。您还希望它在您按下 Tab 键时循环显示按钮,如果它们在最后一个按下 Tab 键时返回顶部。如果某个按钮获得焦点,则单击它,如果没有,则转到第一个按钮。

试试这个:

$(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>