javascript - 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
脚本也可以获取其他链接。href
link-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
函数中,但它仍然只href
得到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>
推荐阅读
- python - pandas groupby 列名部分?
- javascript - 仅在带有 # 的特定 URL 上执行 Javascript
- mediawiki-api - 对 wikimedia api 的哪些查询允许获取文章类别?
- list - 如何在字典中为 default_get 方法 Odoo11 插入列表值
- testing - 哪种算法适用于使用“机器学习”预测多个输出值
- javascript - 将数据从 aws S3 加载到 jstree
- http - Charles:如何记录http请求排除OPTIONS模式?
- angular - 哪个更适合 css(Bootstrat 或自己的 CSS)、动画、以 Angular 6 启动新项目的组件?
- vue.js - 道具值没有在 axios 内更新
- c# - 如何在 Web API 中接收表单数据并处理数据