我想检测用户是否使用jQuery按下了Enter键。

这怎么可能?它需要插件吗?

看起来我需要使用keypress()方法。

该命令是否存在浏览器问题?比如,是否存在我应该知道的浏览器兼容性问题?


当前回答

这就是我解决问题的方法。你应该使用return false;

$(document).on('按键',函数(e){如果(e.whit==13){$('#sub_btn').触发器('click');alert('您在某处按下了“Enter”键');return false;}});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><form action=“”method=“post”id=“sub_email_form”><div class=“modal header”><button type=“button”class=“close”id=“close”数据消除=“mode”>&times</按钮><h4 class=“modal title”>订阅我们的技术分析</h4></div><div class=“modal body”><p>注册我们的定期技术分析更新,以查看直接在收件箱中提供的建议</p><div class=“input group”><input type=“email”name=“sub_email”id=“sub_email”class=“form control”placeholder=“Enter your email”required></div><span id=“save error”></span></div><div class=“modal footer”><div class=“input group append”><input type=“submit”class=“btn btn primary sub_btn”id=“sub_btn”name=“sub_btn”value=“Subscribe”></div></div></form>

其他回答

有一个keypress()事件方法。Enter键的ASCII编号为13,不取决于使用的浏览器。

jQuery的要点是您不必担心浏览器的差异。我非常确信,在所有浏览器中,输入值都是13,这是安全的。考虑到这一点,您可以这样做:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

我想出了这个解决方案:

$(document).ready(function(){

  $('#loginforms').keypress(function(e) {
    if (e.which == 13) {
    //e.preventDefault();
    alert('login pressed');
    }
  });

 $('#signupforms').keypress(function(e) {
    if (e.which == 13) {
      //e.preventDefault();
      alert('register');
    }
  });
});

检测用户是否按下Enter键的简单方法是使用键号。Enter键编号等于13。

要检查设备中密钥的值,请执行以下操作:

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // Backspace in Internet Explorer only is on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

按Enter键,结果为13。使用键值,您可以调用函数或执行任意操作:

    $(document).keypress(function(e) {
      if(e.which == 13) {
        console.log("The user pressed the Enter key");

        // The code you want to run
      }
    });

如果您想在按下Enter键后锁定按钮,可以使用以下代码:

$(document).bind('keypress', function(e) {
  if(e.which === 13) { // Return
     $('#buttonname').trigger('click');
  }
});
$(function(){
  $('.modal-content').keypress(function(e){
    debugger
     var id = this.children[2].children[0].id;
       if(e.which == 13) {
         e.preventDefault();
         $("#"+id).click();
       }
   })
});