Javascript 没有在 Chrome 中按 ENTER 键生成 keypress 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14518412/
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
keypress event not generated in Chrome on ENTER Key?
提问by emilly
My application requires an input from users, on entering a value in a textbox, users hit Enter (Return Key) and this calls a buttons onclick event. This works fine in IE, FF but not Chrome. On enter in chrome, keypress event is not generated Here is my code snippet
我的应用程序需要用户输入,在文本框中输入值时,用户按 Enter(回车键),这会调用按钮 onclick 事件。这适用于 IE、FF,但不适用于 Chrome。在 chrome 中输入时,不会生成按键事件这是我的代码片段
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
Could anyone provide input on this?
任何人都可以提供这方面的意见吗?
回答by sdespont
Cross-browsers method :
跨浏览器方法:
$('#myDiv').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13) {
e.preventDefault();
alert("enter pressed");
}
});
Tested on Chrome 24 : http://jsfiddle.net/PTauw/1/
在 Chrome 24 上测试:http: //jsfiddle.net/PTauw/1/
回答by Tim Down
keypressis the correct event for detecting which character has been typed (although in this particular case, that of detecting the enter key, keydownwould work just as well). However, how to get the character typed in a keypress event is inconsistent between browsers, so jQuery normalizes on the whichproperty. Here's what you want:
keypress是检测输入了哪个字符的正确事件(尽管在这种特殊情况下,检测回车键的事件keydown也能正常工作)。但是,如何获取 keypress 事件中键入的字符在浏览器之间是不一致的,因此 jQuery 对which属性进行了规范化。这是你想要的:
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.which == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
The definitive reference for key events: http://unixpapa.com/js/key.html
关键事件的权威参考:http: //unixpapa.com/js/key.html
回答by Vaibs_Cool
This link might be helpful for you...
Api Jquery Key Pressor try with this code
此链接可能对您有所帮助...
Api Jquery Key Press或尝试使用此代码
Change keypress to keydown:
将 keypress 更改为 keydown:
$('#myDiv').keydown(function(e) {
// your logic
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
回答by echo_Me
Chrome seems to be working with ENTERkey and not 13.
Chrome 似乎正在使用ENTERkey 而不是13.
this works for me on all browsers including CHROME.
这适用于所有浏览器,包括CHROME.
$('#myDiv').keydown(function(e) {
if ((e.which == 13) || (e.which == keyCode.ENTER)) {
alert("enter pressed");
}

