且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按键事件中的输入验证

更新时间:2022-05-14 08:10:25

如果您要检查可打印的键,这正是您似乎在做的事情,应该改用 keypress 事件,因为这是您唯一可以获得可靠信息的地方按键代表的字符。在 keydown 事件中,您无法可靠地检测到数字按键。另外,抑制箭头键和删除/退格键也是个坏主意。这样做有什么好处?

If you're checking a printable key, which is exactly what you seem to be doing, you should use the keypress event instead, since that's the only place you're going to be able to get reliable information about the character the keypress represents. You can't detect numeric keypresses reliably in the keydown event. Also, it's a bad idea to suppress arrow keys and delete/backspace keys. What do you gain from doing that?

还有一些错误:在Firefox中,您需要获取 Event 来自传递给事件处理函数的参数的对象,如果您使用的是DOM0事件处理函数,而不是 addEventListener() attachEvent (),则应使用 return false; 禁止默认行为。这是我推荐的代码:

There's also some errors: in Firefox, you'll need to get the Event object from the parameter passed into the event handler function, and if you're using a DOM0 event handler function rather than addEventListener() or attachEvent(), you should use return false; to suppress default behaviour. Here's my recommended code:

var input = document.getElementById("your_input_id");

input.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    var charStr = String.fromCharCode(charCode);
    if (/\d/.test(charStr)) {
        return false;
    }
};