Jquery keypress()事件对keyup()不起作用

jquery keypress() events are not working for keyup()

本文关键字:keyup 不起作用 事件 Jquery keypress      更新时间:2023-09-26

这是按键功能的代码,它只允许数字http://jsfiddle.net/lesson8/HkEuf/1/

但是,对于相同的键码,keyup函数不起作用。我的意思是,如果我用

$(document).ready(function () {
  //called when key is pressed in textbox
  $("#quantity").keyup(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

使用keyup的原因是获取文本框中当前输入的值。如果我使用keyup函数,我将得到当前的值。但是,如果我使用keydown或keypress,我将获得文本框中先前或现有的值请参阅带有不同函数的更新代码http://jsfiddle.net/dgireeshraju/HkEuf/7300/这是keydown的例子,它给出了现有的值。

KeyUp仅在插入字符后触发,因为您可以看到您的函数实际上正在调用并显示警告消息。

如果你用KeyDown尝试相同的代码,它将工作,因为事件将在插入字符之前被调用

//called when key is pressed in textbox
  $("#quantity").keydown(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });

Key up在键的默认操作>完成后,当用户释放一个键时触发。

Keypress在插入实际字符时触发,例如>文本输入。当用户按下键时,它会重复。

Your code is actaully working in both the cases (you can see the error message atleast ),但由于这个事件是不同的,所以是结果。要使它与keyup一起工作,您需要再次清空input元素,因为此时值已经在input元素

中输入了。
   $("#quantity").keyup(function (e) {
    //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $(this).val(''); //<--- this will empty the value in the input.
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
        return false;
    }
});

注意:然而,清空输入会删除完整的值,即使其中有数字,所以在这种情况下,我更喜欢keydown

这是对输入值的一个小hack,但是(我仍然更喜欢用keydown),如果你真的想要keyup工作的话,使用这个:)。由于我正在修改浏览器的默认行为,因此您可能还需要考虑许多其他情况。

$("#quantity").keyup(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
     if(e.which != 13){ //<--- don't remove when entered is pressed.
        $(this).val(e.currentTarget.value.substr(0, e.currentTarget.value.length - 1));
    }
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
}
console.log(e.currentTarget.value);
});
工作小提琴