我的页面上有一些外部链接
<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-1
的ext
。
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
函数中,但它仍然仅获得href
的link-1
。我不知道脚本的其余部分是否与问题有关。这是非常基本的操作,只是剥离退出页面并自动转发到目的地。但是,即使使用each
函数,这怎么也无法按预期运行?
您可以更改每个链接的href
属性,可以将.attr()
与回调函数一起使用,该回调函数为您提供当前.attr()
作为第二个参数,您可以将其用作查询字符串:
href
$('.ext').attr('href', function(i, external) {
return 'http://localhost/checkLinkURL?=' + external;
});