jQuery each和attr

albert7838

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

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

我尝试将ext链接定向到退出页面,然后自动将其重定向到目标。它工作正常,但有多个ext网页上的链接,我的脚本获得hreflink-1其他ext链接了。

因此:

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

尼克·帕森斯

您可以更改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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章