Jquery keypress()事件对keyup()不起作用
jquery keypress() events are not working for keyup()
这是按键功能的代码,它只允许数字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);
});
工作小提琴- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- jQuery调用keyup事件不起作用
- jquery keyup removeClass没有'不起作用
- Keyup事件在easyui上不起作用
- .keyup() 上的非拉丁字符替换在快速键入时不起作用
- jQuery获取keyup上带有类的输入的ID不起作用
- jQuery keyup 函数不起作用
- Jquery keyup 在 Android 上不起作用
- CSS 悬停在 KEYUP 函数执行后不起作用
- jquery keyup()延迟不起作用
- Jquery keyup函数不起作用
- .keyup jquery在Iphone上不起作用
- jQuery keyup在IE7中不起作用
- keyup功能可以在所有浏览器中正常工作,但仅在IE中不起作用
- Jquery keypress()事件对keyup()不起作用
- 在Java脚本验证中,使用keyup进行验证在mozilla中不起作用
- ng-keyup preventDefault()不起作用
- jQuery:dblclick上的触发事件不起作用(但在keyup等上起作用)
- Keyup对一些动态创建的内容不起作用