我今天发现按下Enter键时不会触发keypress事件,因此您可能想改用keydown()或keyup()。
我的测试脚本:
$('.module input').keydown(function (e) {
var keyCode = e.which;
console.log("keydown ("+keyCode+")")
if (keyCode == 13) {
console.log("enter");
return false;
}
});
$('.module input').keyup(function (e) {
var keyCode = e.which;
console.log("keyup ("+keyCode+")")
if (keyCode == 13) {
console.log("enter");
return false;
}
});
$('.module input').keypress(function (e) {
var keyCode = e.which;
console.log("keypress ("+keyCode+")");
if (keyCode == 13) {
console.log("Enter");
return false;
}
});
在键盘上键入“ A Enter B”时,控制台中的输出:
keydown (65)
keypress (97)
keyup (65)
keydown (13)
enter
keyup (13)
enter
keydown (66)
keypress (98)
keyup (66)
您会在第二个序列中看到'keypress'丢失了,但是按下/释放了keydown和keyup寄存器代码'13'。根据关于功能keypress()的jQuery文档:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
在Server 2012 R2的IE11和FF61上测试