【问题标题】:keydown function assigned to two keys but is fired when any key is pressedkeydown 函数分配给两个键,但在按下任意键时触发
【发布时间】:2019-01-15 17:16:09
【问题描述】:

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

【问题讨论】:

  • 能否请您发布您尝试过但没有成功的代码。

标签: javascript jquery keypress keydown


【解决方案1】:

问题源于您使用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');
        }
    });

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

【讨论】:

  • 太棒了!这对我有用。我非常感谢您的帮助,我很高兴有一个社区可以提供帮助。朋友,加油!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
相关资源
最近更新 更多