[英]jQuery javascript keypress function not working on IE8
I've the following jquery function which avoid typing "1" in the input text: 我有以下jquery函数,避免在输入文本中键入“1”:
<input id="myId" style="width:50%;" value="0" type="text">
$("#myId").keypress(function(e) {
var x=e.charCode;
if (x == '49'){
e.preventDefault();
}
});
This is the jsfiddle 这是jsfiddle
which is not working on IE8. 哪个不适用于IE8。 Where is my error?
我的错误在哪里? Thanks in advance!
提前致谢!
EDIT JAVASCRIPT VERSION 编辑JAVASCRIPT版本
<input id="myId" style="width:50%;" value="0" type="text" onkeypress="javascript:checkNumber(event);"/>
function checkNumber(event) {
var x=e.which;
if (x == 49){
event.preventDefault();
}
}
charCode
is not cross-browser, you can use jQuery which
property: charCode
不跨浏览器,你可以使用jQuery which
属性:
The
event.which
property normalizesevent.keyCode
andevent.charCode
.该
event.which
财产归event.keyCode
和event.charCode
。 It is recommended to watchevent.which
for keyboard key input.建议观看
event.which
键盘输入键。
var x = e.which;
If you don't use jQuery, you can code: 如果你不使用jQuery,你可以编码:
var x = e.charCode || e.keyCode;
See this answer to a similar question. 查看类似问题的答案 。 Try
keydown
instead of keypress
and keyCode
instead of charCode
: 尝试使用
keydown
而不是keypress
和keyCode
而不是charCode
:
$("#myId").keydown(function(e) {
var x=e.keyCode;
if (x == '49'){
e.preventDefault();
}
});
the jQuery documentation for keypress lists a few good reasons to use keydown
instead, not the least of which is that it only fires once for a press and hold, and keypress reports the character, not the key (which is problematic when dealing with things like capslock.) 按键的jQuery文档列出了使用
keydown
的一些很好的理由,其中最重要的是它只会触发一次按住,而keypress会报告字符,而不是密钥(这在处理类似事情时会出现问题)大写锁定。)
Use e.which
instead, since e.charCode
isn't supported on all browsers. 请改用
e.which
,因为并非所有浏览器都支持e.charCode
。
Also, you might consider using .keyup()
event instead of .keypress()
此外,您可以考虑使用
.keyup()
事件而不是.keypress()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.