我有外部链接<a href="http://notmysite.com/">Link</a>
我需要在外部链接的href之前添加:http://myurl.com?url=
。
制作它<a href="http://myurl.com/current/page?url=http://notmysite.com/">
我目前的js代码:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$('a:external').addClass('external').attr("href", window.location+("href"));
它不起作用。我猜这是语法。
我对jquery很新,所以更喜欢这个更脏/更直接的方法
干杯!
答案 0 :(得分:2)
请尝试以下操作,在将网址附加到网关网址之前,请注意escape
网址,并略微优化:
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");
}
});
答案 1 :(得分:1)
以下内容:
$("a[href^='http:']:not([href*='"+window.location.host+"'])").each(function(){
$(this)
.attr("href","http://mysite.com?url="+$(this).attr("href"))
.addClass("external");
});
此HTML:
<a href="http://www.google.com">Google</a>
<a href="http://localhost/somepage.html">Localhost</a>
成为这个:
<a class="external" href="http://mysite.com?url=http://www.google.com">Google</a>
<a href="http://localhost/somepage.html">Localhost</a>
答案 2 :(得分:1)
以下是我们在insightcruises.com
上使用的内容,它将所有出站网址重写为前缀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);
};