keydown 函数分配给两个键,但在按下任意键时触发

keydown function assigned to two keys but is fired when any key is pressed

问:我只将 keydown 分配给了 2 个键,但是,如果我按下任何键盘键,脚本就会被触发。有人可以通过查看脚本告诉我这是否是格式问题吗?

这个 keydown jQuery 对我有用,当按下右箭头时,模态移动到下一个,当按下左键时,它将触发前一个模态。

$("div[id^='myModal']").keydown(function(e){
    var currentModal = $(this);
    if (e.which == 39){
    }else{
  currentModal.modal('hide');
  currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');  
    }
     var currentModal = $(this);
    if (e.which == 37){
    }else{
  currentModal.modal('hide');
  currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
    }
});

问题源于您使用 if 语句。在我看来,您似乎应该更改代码:

$("div[id^='myModal']").keydown(function(e){
        var currentModal = $(this);
        if (e.which === 39) {
          currentModal.modal('hide');
          currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');  
        } else if (e.which === 37) {
          currentModal.modal('hide');
          currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
        }
    });

基本上,您的代码所说的是 "If the left arrow key is pressed do nothing, otherwise do something with the previous modal",然后是 "If the right arrow key is pressed do nothing, otherwise do something with the next modal"。