英语吧简友广场每天写1000字

Three Most Common jQuery Events

2019-07-26  本文已影响45人  此之木

Keypress

In jQuery, keypress() method is a quick and easy way to add a key press listener to element(s).

I updated the HTML a little bit by adding a simple text input. 

If I want to get a print message every time when I press the key in the input, I will write keypress() function:

$(“input”).keypress(function(){

console.log(“You Pressed A Key!”);})

So no matter what key I press, the console will print out the message right after I pressed the key.

If we want to listen for a key press only we hit the “Enter” key, we need to check the key code for enter key first.

The key code for “Enter” is 13. Therefore, we can write an if function in the keypress():

$(“input”).keypress(function(event){

if(event.which === 13) {

alert(“You Hit Enter”);}})

上一篇 下一篇

猜你喜欢

热点阅读