[英]How to detect when an enter is pressed using jQuery?
I am trying to detect what key is pressed and based on that I want to fire click()
event. 我正在尝试检测按了什么键,并据此触发了click()
事件。
My code work for all the key except for the enter. 我的代码适用于除Enter之外的所有键。
for some reason when I press "enter" I do not get any messages on the screen as if the enter button was not pressed. 由于某些原因,当我按下“输入”时,屏幕上没有收到任何消息,好像没有按下输入按钮一样。
Here is my code 这是我的代码
$(function(){
$(document).keypress(function(e) {
handleKeyPress(e);
});
function handleKeyPress( e ){
var key = e.which;
alert(key);
if( getIcwsTabIndex() != 1){
return;
}
if( key >= 48 && key <= 57){
var k = key - 48;
$('#icwsDialerNumber' + k).click();
}
if( key == 8){
e.preventDefault();
$('#icwsDialerScreenDel').click();
}
if( key == 13){
e.preventDefault();
$('#icwsDialerNumberDial').click();
}
}
});
what am I doing wrong here? 我在这里做错了什么?
tested your code, it works on chrome besides the not defined getIcwsTabIndex 测试了您的代码,除了未定义的getIcwsTabIndex之外,它还适用于chrome
so verify it is ok on your side 所以确认在你这边还可以
here is a fiddle check the console 这是一个小提琴检查控制台
$(function(){
$(document).keypress(function(e) {
handleKeyPress(e);
});
function handleKeyPress( e ){
var key = e.which;
console.log(key);
// if( getIcwsTabIndex() != 1){
// return;
// }
if( key >= 48 && key <= 57){
var k = key - 48;
$('#icwsDialerNumber' + k).click();
}
if( key == 8){
e.preventDefault();
$('#icwsDialerScreenDel').click();
}
if( key == 13){
e.preventDefault();
console.log(key);
$('#icwsDialerNumberDial').click();
}
}
});
The problem with your code is that is not cross-browser. 您的代码的问题在于它不是跨浏览器。 It should be: 它应该是:
var key = e.charCode || e.keyCode || 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.