Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

javascript - is there a function to do on a specific keypress instead of click

i was wondering if there is a function i could use instead of using a mouse click as i have set keybinds to whenever i press it it does it on my pc , here is my code i am using for a broswer script on tampermonkey,

        }
        $('.pagination.prev').on('click' , function(e){
            e.preventDefault();
            setTimeout(function(){
                getPlayerDataFromSite();
            }, 500);
        });

        $('.pagination.next').on('click' , function(e){
            e.preventDefault();
            setTimeout(function(){
                getPlayerDataFromSite();
            }, 500);
        });
    }

instead of using mouse click on the next button and previous button i would like it to use b key as previous and n key as next

thanks in advance for help really appriciate it

question from:https://stackoverflow.com/questions/66054986/is-there-a-function-to-do-on-a-specific-keypress-instead-of-click

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Handling a 'keydown' event is rather simple.

You simply listen for the event, then check for the key you are interested in.

For example, this code listens for the keys "b" and "n":

const pre = document.querySelector('pre');
pre.innerText = "";

window.addEventListener('keydown', event => {
  // console.log('keydown event:', event);
  pre.innerText += `keydown event.key: "${event.key}"
`;
  if (event.key === 'b') {
    alert('You pressed "b"');
  } else if (event.key === 'n') {
    alert('You pressed "n"');
  }
});

document.querySelector('button').onclick = () => {pre.innerText = ""};
<h4>Logging 'keydown' Events</h4>
<button>Clear Log</button>
<pre></pre>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...