How do I use a jQuery not selector to select relative URLs?
I'm working on a little jQuery script to add Google Analytics pageTracker onclick data to all relative URLs on my forum, allowing me to track clicks to external sites.
I don't want to add the onclick to internal links on forum.sitename or sitename, and I don't want to add them to any hrefs marked # or that start with /. My script below works nicely, but for one minor problem!
All of the forum's URLs are relative and don't start with /. I appear to have no way to change that, so need to modify the jQuery below to prevent it adding the onclick to links like as it currently does.
What I want to do, is to write a .not() function like .not("[href!^=http") to prevent jQuery from adding the onclick to any hrefs which do not start with http. However, .not() appears not to support this.
I'm new to jQuery and can't figure this out. Any pointers would be massively appreciated.
$(document).ready(function(){
// Get URL from a href
var URL = $("a").attr('href');
// Add pageTracker data for GA tracking
$("a")
.not("[href^=#]")
.not("[href^=http://forum.sitename]")
.not("[href^=http://www.sitename]")
.attr(开发者_开发知识库"onclick","pageTracker._trackEvent('Outgoing_Links', 'Forum', " + URL + ");")
;
});
Thanks!
You can write the not selector like this to get the links that do start with http
, but don't contain "sitename.com":
$('a[href^=http]:not([href*="sitename.com"])')
You can play with an example here, this uses the string based :not()
selector and the ^=
attribute starts-with selector you're already using and the *=
attribute contains eelector.
Update based on comments:
$(functon() {
$('a[href^=http]:not([href*="sitename.com"])').click(function() {
pageTracker._trackEvent('Outgoing_Links', 'Forum', this.href);
});
});
var regex = RegExp('^(?:f|ht)tps?://(?!' + location.hostname + ')');
$('a').filter(function(){
// Filter-out internal links
return regex.test(this.href);
}).click(function(){
pageTracker._trackEvent('Outgoing_Links', 'Forum', this.href);
})
精彩评论