0

キャラクターを正規表現で監視したい。

$('#searchContent').keyup(function(e){

        e = e || window.event;

        var patt =/\w/g;
        var key = String.fromCharCode(e.keyCode);


        console.log ( "key " + key + e.keycode+ " is pressed!!");

        if( e.keycode != 8 && e.keyCode != 46){ //Will return if printable char is not typed. But the datagrid will still refresh on  pressing backspace.
            console.log ( "key " + key+ e.keycode + "is about to take test!!" );
            if(!patt.test(key)){ 
                console.log ( "key " + key+e.keycode + "is failed!!");
                return;
            }
            console.log ( "key " + key +e.keycode+ "is pressed passes the test!!");
        }
        else{
            console.log ( "backspace or delete has ByPasses the conditoin!!");
        }
          //  other operations....
}
    //Result of my log. INPUT : RIS(<-backspace)
    key R undefined is pressed!! index_tab.php:173
    key R undefined is about to take test!! index_tab.php:176
    key R undefined is pressed passes the test!! index_tab.php:181
    key I undefined is pressed!! index_tab.php:173
    key I undefined is about to take test!! index_tab.php:176
    key I undefined is pressed passes the test!! index_tab.php:181
    key S undefined is pressed!! index_tab.php:173
    key S undefined is about to take test!! index_tab.php:176
    key S undefined is pressed passes the test!! index_tab.php:181
    key  undefined is pressed!! index_tab.php:173 //here backspace was pressed
    key  undefined is about to take test!! index_tab.php:176
    key  undefined is failed!! 
4

1 に答える 1

7

つまり、JavaScriptでは大文字と小文字が区別されます。

e.keycode != e.keyCode.

そして、キャメルケースを使用する必要があります-e.keyCode

$記号が jQuery だとすると、コードを調べるときに使用することをお勧めしe.whichます。すべてのブラウザと互換性があるように正規化されています。

ここを参照してください: http://api.jquery.com/event.which/、基本的にソースは次のとおりです。

// Add which for key events
if ( event.which == null ) {
    event.which = original.charCode != null ? original.charCode : original.keyCode;
}
于 2013-03-22T09:05:07.727 に答える