Kyle Gobel
Kyle Gobel

Reputation: 5750

Using jquery to change hyperlinks

I'm trying to make a tracking system and am a bit of jquery noob.

Pretend I have this

<div class="ads">
<a href="http://www.google.com">Google</a>
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>

I want to replace the urls with my own, that first go to some page to track the click, such as

http://www.mysite.com/TrackClick/?url=http://www.google.com

http://www.mysite.com/TrackClick/?url=http://www.stackoverflow.com

Obviously with the proper encoding.

I thought I could do something like..

$(".ads").find("a").attr("href", "http://www.mysite.com/TrackClick/?" + $(this).attr("href") );

but that doesn't work...and I'm not really sure why

Thanks for any help.

Upvotes: 1

Views: 146

Answers (4)

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15433

The reason is that the this is not deffined inside the attr() function.

Use .each() function instead.

$(".ads a").each(function(){
    $(this).attr( 'href', 'http://www.mysite.com/TrackClick/?' + $(this).attr('href') );
});

Take a look at

http://jsfiddle.net/H34yX/1/

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117314

this is not pointing to the link inside your code.

You may use a function to set the attribute:

$(".ads")
.find("a")
 .attr("href", function(i,a)
               {return "http://www.mysite.com/TrackClick/?"+encodeURIComponent(a)} );

Upvotes: 2

MacMac
MacMac

Reputation: 35301

My working code:

http://jsfiddle.net/ZAhkK/

$('.ads a').each(function(){
   $(this).attr('href', 'http://www.mysite.com/TrackClick/?' + $(this).attr('href'));
});

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

try this:

$(".ads a").each(function() {
    $(this).attr("href", "http://www.mysite.com/TrackClick/?" + $(this).attr("href"));
});

You need to loop through the selection to change attributes relative to themselves, the .each method does that :)

Upvotes: 0

Related Questions