首页 > 解决方案 > 在 div 中的页面上显示 HREF 链接

问题描述

我想用一些greasemonkey脚本的先前链接中的href链接替换或附加h2标签中的文本。例如,我有十个这样的链接:

<div class="cml">This is some <a href="www.link1.com">SomeLinkText1</a></div>
<h2 class="legend">Some text 1</h2>
<div class="cml">This is some <a href="www.link2.com">SomeLinkText2</a></div>
<h2 class="legend">Some text 2</h2>
...

我需要它是:

<div class="cml">This is some <a href="www.link1.com">SomeLinkText1</a></div>
<h2 class="legend">Some text 1 - www.link1.com</h2>
<div class="cml">This is some <a href="www.link2.com">SomeLinkText2</a></div>
<h2 class="legend">Some text 2 - www.link2.com</h2>
...

所以,我只想提取页面上的所有href并将它们显示在h2或一些新的div中(不管在哪里,它也可以是同一个标签中SomeLinkText的INSTEAD) - 例如:

<div class="cml">This is some <a href="www.link1.com">www.link1.com</a></div>
<div class="cml">This is some <a href="www.link2.com">www.link2.com</a></div>
...

我对javascript很弱。我在这里使用搜索并找到了一些答案,但它仅适用于第一个链接。

$('.legend').html($('.cml a').prop('href'));

有人可以帮助我编写代码,以便我可以动态地在页面上显示 href 吗?

谢谢你。

标签: javascriptjqueryhtmlhref

解决方案


可以使用text(function)which 将遍历每个实例。函数内部this是当前元素实例,您可以使用它遍历前一个元素以获取相应的 href

$('.legend').text(function(index, currText) {
  var linkUrl = $(this).prev('.cml').find('a').attr('href');
  return currText + ' - ' + linkUrl;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cml">This is some <a href="www.link1.com">SomeLinkText1</a></div>
<h2 class="legend">Some text 1</h2>
<div class="cml">This is some <a href="www.link2.com">SomeLinkText2</a></div>
<h2 class="legend">Some text 2</h2>


推荐阅读