简体   繁体   中英

Bind arrow keys to navigation with jQuery

For the purposes of this test I have some basic html:

<a href="https://www.google.co.uk" class="prev">Previous</a>
<a href="https://jsfiddle.net" class="next">Next</a>

I have a fairly straightforward jquery function:

var prev = $('.prev');
var next = $('.next');

$('body').on('keydown',function(e){
    if(e.which == 37){
    prev.trigger('click');
  }else if(e.which == 39){
    next.trigger('click');
  }
  console.log(e.which);
  e.preventDefault();
});

The console is logging each key pressed, however this is not binding the click event to each of the href's and I am not sure why.

In addition I think using e.preventDefault(); is stopping other key actions on the page. In the other keyCode functions in my app I am not using return false or preventDefault();

Is it possible to wrap the anchors in a div and bind the keydown only to that container for example:

<div class="nav">
   <a href="https://www.google.co.uk" class="prev">Previous</a>
   <a href="https://jsfiddle.net" class="next">Next</a>
</div>

 $('.nav').on('keydown', function(){} // etc

I have a jsfiddle here: https://jsfiddle.net/lharby/sva0a4d1/

You can try this:

$('body').on('keydown',function(e){
    if(e.which == 37){
        $('a.prev')[0].click()
  }else if(e.which == 39){      
        $('a.next')[0].click()
  }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM