1

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.

1
  • 1
    Be aware that users without JavaScript enabled won't be tracked but I am guessing you have already thought about this :) Commented Aug 2, 2011 at 11:20

4 Answers 4

2

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)} );
Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

0

My working code:

http://jsfiddle.net/ZAhkK/

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

2 Comments

That's not the same code he posted, you should state that this is a fix :P P.S. beat you by 30 seconds :D
Lol, yeah was meant to change it, but yes you did :O
0

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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.