Jquery each and attr

问题描述 投票:0回答:1

我的页面上有一些外部链接

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

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

Ergo:

// 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函数中,但它仍然仅获得hreflink-1。我不知道脚本的其余部分是否与问题有关。这是非常基本的操作,只是剥离退出页面并自动转发到目的地。但是,即使使用each函数,这怎么也无法按预期运行?

javascript jquery attributes each
1个回答
0
投票

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

href
$('.ext').attr('href', function(i, external) {
  return 'http://localhost/checkLinkURL?=' + external;
});
© www.soinside.com 2019 - 2024. All rights reserved.