jQuery:如何过滤掉keypress事件中的非字符键? [英] jQuery: how to filter out non-character keys on keypress event?

查看:114
本文介绍了jQuery:如何过滤掉keypress事件中的非字符键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试搜索但不确定要查找的字词。

I tried searching but unsure of what terms to look for.

我正在使用jQuery并希望在文本框中使用keypress事件,但阻止所有不可打印的字符(即输入 ESC ,箭头键,退格标签 ctrl 插入 F1 - F12 等)来触发事件。

I'm using jQuery and would like to use the keypress event in a textbox, but prevent all non-printable characters (ie. Enter, ESC, arrow keys, backspace, tab, ctrl, insert, F1-F12, etc) from triggering the event.

是否有一种简单的方法可以确定它是否可打印?

Is there an easy way to determine if it is printable?

推荐答案

此问题的选定答案未完成。它不处理与修饰键一起按下字符键的情况(例如 CTRL - A )。

The selected answer for this question is not complete. It does not handle the case where a character key is being pressed in combination with a modifier key (e.g. CTRL-A).

例如,尝试使用带有以下代码的firefox键入 CTRL - A 。目前的答案将其视为一个字符:

Try, for example, typing CTRL-A using firefox with the following code. The current answer will consider it as a character:

HTML:

<input placeholder="Try typing CTRL-A in Firefox" style="width: 200px"/>

JavaScript:

JavaScript:

$("input").keypress(function (e) {
    if (e.which !== 0) {
        alert(String.fromCharCode(e.which));
    }
});

http://jsfiddle.net/4jx7v/

注意:如果使用某些浏览器(例如Chrome),则不会触发警报他们不会为非字符输入触发按键事件。

Note: an alert won't be fired if using some browsers (such as Chrome), since they don't fire a keypress event for non-character inputs.

更好的解决方案可能是:

A better solution might be:

HTML:

<input placeholder="Try typing CTRL-A in Firefox" style="width: 200px"/>

JavaScript:

JavaScript:

$("input").keypress(function (e) {
    if (e.which !== 0 &&
        !e.ctrlKey && !e.metaKey && !e.altKey
    ) {
        alert(String.fromCharCode(e.which));
    }
});

http://jsfiddle.net/hY5f4/

在这种情况下,只有在 A 时才会触发警报所有浏览器都按了 CTRL - A

In this case, the alert is only being fired when A is pressed, not CTRL-A for all browsers.

这篇关于jQuery:如何过滤掉keypress事件中的非字符键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆