简体   繁体   中英

Getting Href From Hyperlink Text in Javascript/JQuery

I am trying to write a Tampermonkey script to help the navigation of some of the websites I commonly browse. The goal is to be able to browse through the pagination of the page with the arrow keys (for instance, if I am on page 3, left key would go to page 2). I want to be able to search the page to ensure the Previous link exists, and if it does, click it to go to the previous page. An example would be as follows:

<a href="www.example.com/page/2.html>Previous</a>

Instead of parsing the url to get the "2" as an integer, incrementing or decrementing as needed, and reconstructing the url, I want to find the word "Previous" and click it if it exists. How would I go about doing this? Thank you much for your time!

This is somewhat what I am looking for: http://runnable.com/UhZCuuHhSAsoAALM/how-to-get-a-href-value-using-jquery However, the code uses

var href = $('a:first').attr('href');

to get the first href on the page. I need it to get a specific href on the page (one titled "Previous").

Moving backward and forward through the user's history is done using the back(), forward(), and go() methods.

window.history.back();
window.history.forward();

Check out MozDev

<body id="body" data-page='2'>...

javascript

var num = document.getElementById('body').getAttribute('data-page');
document.onkeyup = function(e) {
  if (e.keyCode == 37) {
      window.location.href = "www.example.com/page/"+(num-1)+".html";
  } 
  if (e.keyCode == 39){
      window.location.href = "www.example.com/page/"+(num+1)+".html";
  }
};

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

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