How does jquery determine whether the Enter key is pressed

Jquery method to determine whether the Enter key is pressed: use the keynum method to determine, the code is [$('#textBox').keypress(function(event){var keynum = (event.keyCode ?event.keyC].



This tutorial operation Environment: windows7 system, jquery 3.2.1 version, this method is suitable for all brand computers.

Recommendation: jquery video tutorial

jquery method to determine whether the Enter key is pressed:

In jquery, the following method is used to determine whether the Enter key is pressed ( Enter)

1

2

3

4

5

6

7

8

9

10

11

12

13

$('#textBox').keypress(function(event){ 

    var keynum = (event.keyCode? Event.keyCode: event.which); 

    if( keynum == '13'){ 

        alert('You pressed a "Enter" key in textbox');   

    } 

}); 

   

$(document).keypress(function(event){ 

    var keynum = (event.keyCode? event.keyCode: event.which); 

    if(keynum == '13'){ 

        alert('You pressed a "Enter" key in somewhere');     

    } 

});

Note that Netscape/ Firefox/Opera supports event.which to obtain the ASCII code of the key, while IE supports both event.keyCode and event.which.

Finally, the process of obtaining keynum can also be judged using if.

Supplement: jQuery gets Ctrl + Enter Shift + Enter

. The keyboard events are corrected in jQuery. You can pass in the event when calling the function. The key code can be found through the which of the event. But when there are key combinations, you need to pay attention.

For example, Ctrl + Enter, although e.ctrlKey is used, the key code of the Enter key is not always 13.

In FireFox, it is judged that Ctrl + Enter is e.ctrlKey && e.which == 13.

In IE6, it is judged that Ctrl + Enter is e.ctrlKey && e.which == 10

Example:

1

2

3

4

5

6

7

$(document).keypress(function(e){

        if(e.ctrlKey && e.which == 13 || e.which == 10) {

                $("#btn").click();

        } else if (e.shiftKey && e.which==13 || e.which == 10) {

                $("#btnv").click();

        }         

 })

相关免费学习推荐:javascript(视频)

Guess you like

Origin blog.csdn.net/benli8541/article/details/112847991