简体   繁体   English

输入时未触发jQuery键按下事件

[英]Jquery key press event not triggered on enter

$("#username,#password").keypress(function(e)
    {
        //alert('');
        if(e.keyCode == 13)
        {
            signIn();
        }
    });

The keypress event not calling if the enter button is pressed. 如果按下回车键,则按键事件不会调用。

Try using keyUp event. 尝试使用keyUp事件。

Live Demo 现场演示

$("#username,#password").keyup(function(e){
        //alert('');
        if(e.keyCode == 13)
        {
            signIn();
        }
});

This is also working with keypress 这也适用于按键

Live Demo 现场演示

$("#txt1").keypress(function(e) {

    if (e.keyCode == 13) {
        //signIn();
        alert("keypress");
    }
});​

Key down is more appropriate: 按下键更合适:

$("#username,#password").keydown(function(e){
        if(e.keyCode == 13)
        {
            signIn();
        }
});    
  1. Use e.which instead of e.keyCode because this is what jQuery guarantees to be on event 使用e.which代替e.keyCode ,因为这是jQuery的保证是事件
  2. Try e.preventDefault() , because without it (if they are in a form) the form submits 尝试使用e.preventDefault() ,因为如果没有它(如果它们在表单中),则该表单将提交
  3. Maybe the best would be listening on form's submit event 也许最好的办法是监听表单的submit事件

Are you sure it's not the signIn (); 您确定它不是signIn (); function that's faulty? 功能有问题吗? Because this seems to work just fine; 因为这似乎很好用; http://jsfiddle.net/vDkBs/1/ http://jsfiddle.net/vDkBs/1/

Use keypress and which statement: 使用按键和以下语句:

$("#username,#password").keypress(function(e) {
    if (e.which == 13) {
        //call here your function
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM