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

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

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

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


当前回答

您可以使用jQuery“keydown”事件处理程序执行此操作:

$("#start").on("keydown", function(event) {
  if(event.which == 13)
    alert("Entered!");
});

其他回答

$(document).keyup(function(e) {
    if(e.key === 'Enter') {
        //Do the stuff
    }
});

这就是我解决问题的方法。你应该使用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,不取决于使用的浏览器。

$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});

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

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