我想检测用户是否使用jQuery按下了Enter键。
这怎么可能?它需要插件吗?
看起来我需要使用keypress()方法。
该命令是否存在浏览器问题?比如,是否存在我应该知道的浏览器兼容性问题?
我想检测用户是否使用jQuery按下了Enter键。
这怎么可能?它需要插件吗?
看起来我需要使用keypress()方法。
该命令是否存在浏览器问题?比如,是否存在我应该知道的浏览器兼容性问题?
当前回答
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
其他回答
我发现这更适合跨浏览器:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
有一个keypress()事件方法。Enter键的ASCII编号为13,不取决于使用的浏览器。
检测用户是否按下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');
}
});
这就是我解决问题的方法。你应该使用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”>×</按钮><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>
我无法使Paolo Bergan蒂诺发布的代码正常工作,但当我将其更改为$(document)和e.which而不是e.keyCode时,我发现它工作得很完美。
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed Enter!');
}
});
链接到JS Bin上的示例