Javascript jQuery:如何过滤掉按键事件上的非字符键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2284844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:37:04  来源:igfitidea点击:

jQuery: how to filter out non-character keys on keypress event?

javascriptjquerykeypress

提问by twig

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

我尝试搜索,但不确定要查找哪些术语。

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.

我正在使用 jQuery 并希望在文本框中使用 keypress 事件,但要防止所有不可打印的字符(即EnterESC、箭头键、backspacetabctrlinsertF1-F12等)触发该事件。

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

有没有简单的方法来确定它是否可打印?

采纳答案by Daniel

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).

此问题的所选答案不完整。它不处理字符键与修饰键(例如CTRL- A)组合按下的情况。

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

例如,尝试输入CTRL- Ausing firefox 和以下代码。当前的答案将其视为一个字符:

HTML:

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/

http://jsfiddle.net/4jx7v/

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.

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

A better solution might be:

更好的解决方案可能是:

HTML:

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/

http://jsfiddle.net/hY5f4/

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

在这种情况下,警报仅在A按下时触发,而不是CTRL-A适用于所有浏览器。

回答by Andras Vass

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

Seems to work just fine with jQuery 1.4.2, FF, IE, Chrome.

似乎在 jQuery 1.4.2、FF、IE、Chrome 上工作得很好。

To delve into the mess that is JS keyboard event handling, see: JavaScript Madness: Keyboard Events

要深入了解 JS 键盘事件处理的混乱,请参阅: JavaScript Madness: Keyboard Events



Updated to filter ctrl, meta & alt key combinations as per Daniel's comment.

更新以根据Daniel 的评论过滤 ctrl、meta 和 alt 键组合。

回答by Marian

Checking for key combinations will not be the best solution in all cases. For example, if you use a key combinations to type a character, that will block the onkeypressevent, when it shouldn't.

在所有情况下,检查组合键并不是最好的解决方案。例如,如果您使用组合键键入一个字符,则会阻止该onkeypress事件,而该事件不应该发生。

Try that here and you will see that it will not work: http://jsfiddle.net/4jx7v/

在这里试试,你会发现它不起作用:http: //jsfiddle.net/4jx7v/

(On a Mac, try alt + a letter and on Windows, try alt + a series of numeric keys.)

(在 Mac 上,尝试 alt + 一个字母,在 Windows 上,尝试 alt + 一系列数字键。)

An alternative to that would be to simply check if the input value has changed from the previous one, that way, you know for sure that something was typed.

另一种方法是简单地检查输入值是否与前一个值相比发生了变化,这样,您就可以确定输入了某些内容。

JavaScript:

JavaScript:

var previousValue;
$("input").keypress(function (e) {
    if (previousValue != $(this).val()) {
        alert('Something has been typed.');
    }
});

回答by de hart

If you only want to do something when the input of the field actually changes you should use the inputevent instead of the keypressevent. If you want to support IE < 9 these days, you will need its propietary propertychangeevent as well.

如果您只想在字段的输入实际更改时执行某些操作,则应使用input事件而不是keypress事件。如果你现在想支持 IE < 9,你还需要它的专有propertychange事件。

In jQuery you can use it like this:

在 jQuery 中,您可以像这样使用它:

$('input').on('propertychange input', function (e) {
    // will fire directly but only when input changes
});

回答by Catfish

You can use regular expressions like this

您可以使用这样的正则表达式

$('something').keypress(function(e) {
    if(e.match(YourRegularExpressionHere)) {
        //do something
    } 
});

This will only do something if it matches the regular expression.

如果它匹配正则表达式,这只会做一些事情。

Have a look at regular expressions. http://www.regular-expressions.info/javascript.html

看看正则表达式。 http://www.regular-expressions.info/javascript.html