简体   繁体   中英

Jquery left right navigation not working

I have the following simple html page:

<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).keydown(function(e){
    if (e.keyCode == 37) {  // left
       $('#prev').click();   
       return false;
    } else if (e.keyCode == 39) {  // right
       $('#next').click();
       return false;
    }
});
</script>
</head>

<body>
<a id="next" href="/next">next</a>
<a id="prev" href="/prev">prev</a>
</body>

</html>

I want to make users navigate articles using right and left keyboard keys. So clicking the left arrow should go to the /prev link and clicking the right arrow should go to the /next link. It's not working in any browser for some reason I can't get.

Thanks

Like this:

$(document).keydown(function(e){    
    if (e.keyCode == 37) {  // left
       window.location.href = $('#prev').attr('href');   
       return false;
    } else if (e.keyCode == 39) {  // right
       window.location.href =  $('#next').attr('href');  
       return false;
    }
});

You're calling .click() on an element, but that doesn't trigger a click event, that's that .trigger() is for:

$(document).keydown(function(e){
    if (e.keyCode == 37) {  // left
       $('#prev').trigger('click');   
       return false;
    } else if (e.keyCode == 39) {  // right
       $('#next').trigger('click');
       return false;
    }
});

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