【问题标题】:Display HREF links on page in divs在 div 中的页面上显示 HREF 链接
【发布时间】:2019-01-14 08:42:39
【问题描述】:

我想用一些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中(不管在哪里,它也可以在同一个a标签中代替SomeLinkText)-例如:

<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 吗?

谢谢。

【问题讨论】:

    标签: javascript jquery html href


    【解决方案1】:

    可以使用text(function) 循环遍历每个实例。函数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>

    【讨论】:

      【解决方案2】:

      或者你可以遍历a并将文本附加到父cim的下一个h2就像

      $('a').each(function(){
        $(this).closest(".cml").next().text($(this).closest(".cml").next().text() + " - "+$(this).attr("href"))
      })
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.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>

      【讨论】:

        【解决方案3】:

        您可以使用jquery的每个函数来迭代每个cml类并将所需的文本附加到h2

        $(".cml").each(function(){
             var linkToAppend = $(this).find("a").attr('href');
             $(this).next().append(" - " + linkToAppend);
        });
        

        【讨论】:

          猜你喜欢
          • 2015-09-13
          • 2017-08-30
          • 2021-07-09
          • 2022-01-22
          • 2011-12-30
          • 1970-01-01
          • 1970-01-01
          • 2015-06-07
          • 1970-01-01
          相关资源
          最近更新 更多