javascript - 在 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 吗?
谢谢你。
解决方案
可以使用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>
推荐阅读
- jsp - 如何将 response.sendRedirect 重定向到弹出窗口?
- elasticsearch - 在数组类型的 ElasticSearch 字段中添加分析器
- python - 如何绘制带有注释的水平堆积条
- react-native - 在现有的 React 应用上实现 Facebook、Instagram、Google 和 Apple 登录
- javascript - Javascript 日期循环错过了几个月
- ios - 为什么某些视图在小部件中显示为红色的禁止进入标志?
- java - 读取消息时,带有 FlinkRunner 的 Apache Beam 管道不会在 PubSub 上发送 ack
- batch-file - 检查连续数字文件名中的错误
- python-3.x - 在 python-selenium 中赋值之前引用的局部变量“浏览器”
- r - 从列表中提取子列表并将其复制到新列表中