Jquery 每个和属性

Jquery each and attr

我的页面中有一些外部 links

<a href="http://example.com/link-1" class="ext">Label</a>
<a href="http://example.com/link-2" class="ext">Label</a>

我尝试将 ext link 定向到退出页面,然后再自动将其重定向到目标。它工作正常,但是页面上有多个 ext link,我的脚本正在为其他 ext link 获取 link-1href我也是。

因此:

// To grab the href of the destination page i.e http://example.com/link-1
var external = $(".ext").attr('href');

// To forward to the exit page first i.e http://localhost/checkLinkURL?=http://example.com/link-1
$(".ext").attr('href', 'http://localhost/checkLinkURL?=' + external);

我已经尝试将代码的第二部分包装在 each 函数中,但它仍然只得到 link-1href。我不知道我的脚本的其余部分是否与问题相关。它非常基本,只是去掉退出页面并自动转发到目的地。但是,即使使用 each 函数,为什么它不能按预期工作?

您可以更改每个 link 的 href 属性,您可以将 .attr() 与回调函数一起使用,它为您提供当前 href 作为第二个参数,您可以将其用作查询字符串:

$('.ext').attr('href', function(i, external) {
  return 'http://localhost/checkLinkURL?=' + external;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="http://example.com/link-1" class="ext">Label</a>
<a href="http://example.com/link-2" class="ext">Label</a>