Py学习  »  Jquery

Jquery each和attr

albert7838 • 4 年前 • 843 次点击  

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

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

ext 链接到退出页,然后自动将其重定向到目标。它工作得很好,但是有多个 提取 页面上的链接,我的脚本正在获取 href link-1 对于其他 链接也是。

因此:

// 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公司 属于 链路-1 每个

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56164
 
843 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Nick Parsons
Reply   •   1 楼
Nick Parsons    4 年前

你可以用 .each() ,并在其回调函数中使用 $(this) 引用当前元素。改变 href 当前链接的属性,使用 .attr() 具有回调函数,该函数提供 href公司 作为第二个参数,可以用作查询字符串:

$('.ext').each(function() {
  $(this).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>