String.fromCharCode(e.which)没有'我认不出点和逗号

String.fromCharCode(e.which) doesn't recognize dot and comma

本文关键字:出点 fromCharCode which 没有 String      更新时间:2023-09-26

我用jQuery:为输入掩码创建了一个函数

$.fn.mask = function(regex) { 
    this.on("keydown keyup", function(e) {
        if (regex.test(String.fromCharCode(e.which))) {
            return false;
        }
    });
}

它根据您传递的正则表达式拒绝任何输入。示例:

$("#textfield").mask(/'s/); // denies white spaces
$("#textfield").mask(/'D/); // denies anything but numbers

上面的例子是有效的,但我尝试使用正则表达式来接受带有小数分隔符的数字,比如:

$("#textfield").mask(/[^'d.,]/); // Anything except digits, dot and comma

这行不通。但如果我在按下.,时在控制台上记录String.fromCharCode(e.which),它会显示这些(相应的)字符:¾¼

问题是为什么String.fromCharCode(e.which)代表那些字符而不是压缩字符?

您想要处理键盘产生的实际字符,而不是键的布局位置。

$.fn.mask = function(regex) { 
    this.on("keypress", function(e) {
        if (regex.test(String.fromCharCode(e.which))) {
            return false;
        }
    });
}

keypress事件报告生成的字符的代码点。

http://jsfiddle.net/USgNJ/