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 tr开发者_开发问答ack 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.
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)} );
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 :)
My working code:
http://jsfiddle.net/ZAhkK/
$('.ads a').each(function(){
$(this).attr('href', 'http://www.mysite.com/TrackClick/?' + $(this).attr('href'));
});
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/
精彩评论