如何在字符串中重复href URL,然后在之间添加额外的字符

时间:2019-01-29 07:39:43

标签: jquery string url

我需要从href获取一个现有的URL,并在其间添加一些额外的字符来重复该URL(以触发弹出窗口)。

例如 <div class="item"><a href="https://website.com"></a></div>

将成为<div class="item"><a href="https://website.com?modal-link=https://website.com"></a></div>

我很确定我使用的术语不正确,因此我的搜索没有得到我想要达到的结果!

先谢谢您了:)

1 个答案:

答案 0 :(得分:1)

您可以使用<a>选择div中类别为item的所有锚标记($('.item a')),然后使用.each遍历每个锚标记。查看特定的定位标记时,您可以使用href来获取其当前的$(this).attr("href"),然后对其进行修改以将链接添加到其末尾。

最后,您可以使用$(this).attr('href', href);

更新当前的定位标记。

请参见下面的工作示例:

$('.item a').each(function() {
  let href = $(this).attr('href'); // get href from the anchor tag
  href += "?modal-link=" + href; // add the query string to it
  $(this).attr('href', href); // update the href attribute
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://website.com">My Link (same)</a>
<div class="item">
  <a href="https://website.com">My Link (changes)</a>
  <br/>
  <a href="https://website2.com">My Link2 (changes)</a>
</div>