jQuery - keydown / keypress /keyup ENTERKEY 检测?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3462995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - keydown / keypress /keyup ENTERKEY detection?
提问by ina
Trying to get jQuery to detect enter input, but space and other keys are detected, enter isn't detected. What's wrong below:
试图让 jQuery 检测回车输入,但检测到空格和其他键,未检测到回车。下面有什么问题:
$("#entersomething").keyup(function(e) {
alert("up");
var code = (e.keyCode ? e.keyCode : e.which);
if (code==13) {
e.preventDefault();
}
if (code == 32 || code == 13 || code == 188 || code == 186) {
$("#displaysomething").html($(this).val());
});
<input id="entersomething" />
<div id="displaysomething"></div>
回答by Russ Cam
JavaScript/jQuery
JavaScript/jQuery
$("#entersomething").keyup(function(e){
var code = e.key; // recommended to use e.key, it's normalized across devices and languages
if(code==="Enter") e.preventDefault();
if(code===" " || code==="Enter" || code===","|| code===";"){
$("#displaysomething").html($(this).val());
} // missing closing if brace
});
HTML
HTML
<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>
回答by Spencer Mark
I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.
我认为您会遇到 keyup 事件 - 因为它首先触发按键 - 如果您想排除 Enter 键,您将无法停止第二个事件的传播。
回答by oriadam
update: nowadays we have mobile and custom keyboards and we cannot continue trusting these arbitrary key codes such as 13 and 186. in other words, stop using event.which
/event.keyCode
and start using event.key
:
更新:现在我们有移动和自定义键盘,我们不能继续信任这些任意键代码,例如 13 和 186。换句话说,停止使用event.which
/event.keyCode
并开始使用event.key
:
if (event.key === "Enter" || event.key === "ArrowUp" || event.key === "ArrowDown")
回答by balupton
jQuery Sparkle includes a custom event for this. The source can be seen here: http://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.events.js
jQuery Sparkle 为此包含一个自定义事件。来源可以在这里看到:http: //github.com/balupton/jquery-sparkle/blob/master/scripts/resources/jquery.events.js
Here is a demo http://www.balupton.com/sandbox/jquery-sparkle/demo/#event-enter
这是一个演示http://www.balupton.com/sandbox/jquery-sparkle/demo/#event-enter