How to add current url with parameters infront of .attr("href")?
I hav开发者_如何学运维e external links <a href="http://notmysite.com/">Link</a>
and I'd need to add: http://myurl.com?url=
before the external link's href.
Making it
<a href="http://myurl.com/current/page?url=http://notmysite.com/">
My current js code:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$('a:external').addClass('external').attr("href", window.location+("href"));
It doesn't work. I'm guessing it's syntax.
I'm rather new to jquery, so would prefer a dirtier/straight forward approach to this
Cheers!
Try the following, which takes care to escape
the URL before appending it to the gateway URL matches more URLs, and is slightly optimized:
var externalLinkPattern = new RegExp("^http://" + window.location.host, "i"),
gateway = "http://myurl.com/current/page?url=";
$("a[href^='http:']").each(function() {
if ( !externalLinkPattern.test(this.href) ) {
this.href = gateway + escape(this.href);
$(this).addClass("external");
}
});
With the following:
$("a[href^='http:']:not([href*='"+window.location.host+"'])").each(function(){
$(this)
.attr("href","http://mysite.com?url="+$(this).attr("href"))
.addClass("external");
});
This HTML:
<a href="http://www.google.com">Google</a>
<a href="http://localhost/somepage.html">Localhost</a>
Becomes this:
<a class="external" href="http://mysite.com?url=http://www.google.com">Google</a>
<a href="http://localhost/somepage.html">Localhost</a>
Here's what we use on insightcruises.com
, which rewrites all outbound URLs as prefixed with http://insightcruises.com/cgi/go/
:
jQuery(function ($) {
$('a[href^=http:]').each(function () {
var $this = $(this);
var href = $this.attr('href');
href = href.replace(/#/, '%23');
var newhref = 'http://insightcruises.com/cgi/go/'+href;
// $('<p />').text(newhref).appendTo('body');
$this.attr('href', newhref);
});
});
window.cgigo = function (url, windowName, windowFeatures) {
if (url.match(/^http:/)) {
url = url.replace(/\#/, '%23');
url = 'http://insightcruises.com/cgi/go/'+url;
};
window.open(url, windowName, windowFeatures);
};
精彩评论