分配给两个键的keydown功能,但在按下任何键时都会触发

时间:2019-01-15 17:16:09

标签: javascript jquery keypress keydown

问:我只将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');
    }
});

1 个答案:

答案 0 :(得分:0)

您使用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');
        }
    });

基本上,您的代码说的是“如果按下左箭头键,则不执行任何操作,否则对上一个模态进行操作”,然后再进行“如果如果按下右箭头键,则不执行任何操作,否则对下一个模态进行操作”