jQuery keyboard navigation – go back and forward a page with left and right

坚强是说给别人听的谎言 提交于 2019-12-10 12:06:09

问题


I'd like the user to be able to load the next or previous page when they press left or right on the keyboard. The next and previous links for each page are contained within two buttons.

The html...

<a href="/page-link-prev" class="prev button">&lt; Prev</a>
<a href="/page-link-next" class="next button">Next &gt;</a> 

Some jquery I found that registers the right key presses, but doesn't change the url obviously, it just shows an alert.

$(function() {
  $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 37 : alert('You pressed Left'); break;
      case 39 : alert('You pressed Right'); break;
    }
  });
});

回答1:


You can use .load() to load from a URL to a portion of the page.

.load( url, [data,] [complete(responseText, textStatus, XMLHttpRequest)] )

Load data from the server and place the returned HTML into the matched element.

I'm assuming you have a specific div you want to refresh w page contents, and you don't want to refresh the entire page

$(function() {
  $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 37 : $('#page').load($(".prev").attr("href")); break;
      case 39 : $('#page').load($(".next").attr("href")); break;
    }
  });
});

Or, if you want to refresh the entire page you can use window.location

Whenever a property of the location object is modified, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.

$(function() {
  $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 37 : window.location = $('.prev').attr('href'); break;
      case 39 : window.location = $('.next').attr('href'); break;
    }
  });
});

You can replace #pagewith the element you are refreshing.




回答2:


I think you have to use the location property of the window object like this:

$(function() {
   $(document).keyup(function(e) {
    switch(e.keyCode) {
      case 37 :
        window.location="/page-link-prev";
      break;
      case 37 :
        window.location="/page-link-next";
      break;
    }
  });
});

Or you can trigger the click event on the jQuery object of your anchor.



来源:https://stackoverflow.com/questions/7706082/jquery-keyboard-navigation-go-back-and-forward-a-page-with-left-and-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!