首页 > 解决方案 > Jquery 每个和 attr

问题描述

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

<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-1ext

尔格:

// 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但是,即使有一个函数,为什么这也不能按预期工作呢?

标签: javascriptjqueryattributeseach

解决方案


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


推荐阅读