Reputation: 19
I have some external links in my page
<a href="http://example.com/link-1" class="ext">Label</a>
<a href="http://example.com/link-2" class="ext">Label</a>
I try to direct the ext
link to an exit page before automatically redirecting it to the destination. It works fine, but with multiple ext
links on the page, my script is getting the href
of link-1
for other ext
links too.
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);
I have tried wrapping the second part of code in an each
function but it still gets only the href
of link-1
. I don't know if the rest of my script is relevant to the problem. It's pretty basic and just strips out the exit page and forwards automatically to the destination. But how come this doesn't work as intended, even with an each
function?
Upvotes: 1
Views: 49
Reputation: 50684
You can change the href
attribute of each link, you can use .attr()
with a callback function which provides the current href
for you as the second argument, which you can use as your query string:
$('.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>
Upvotes: 1