在Javascript/JQuery中从超链接文本获取Href

Getting Href From Hyperlink Text in Javascript/JQuery

本文关键字:超链接 文本 获取 Href Javascript JQuery      更新时间:2023-09-26

我正在尝试编写一个Tampermonkey脚本来帮助导航我经常浏览的一些网站。目标是能够使用箭头键浏览页面的分页(例如,如果我在第3页,左键将转到第2页)。我希望能够搜索页面以确保"上一页"链接存在,如果存在,请单击它转到上一页。一个例子如下:

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

我不想解析url以将"2"作为整数,根据需要递增或递减,然后重建url,而是想找到单词"Previous"并单击它(如果存在)。我该怎么做?非常感谢您抽出时间!

这在某种程度上是我想要的:http://runnable.com/UhZCuuHhSAsoAALM/how-to-get-a-href-value-using-jquery但是,代码使用

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

以获取页面上的第一个href。我需要它在页面上获得一个特定的href(标题为"上一个")。

在用户历史中前后移动是使用back()、forward()和go()方法完成的。

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

查看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";