jQuery为传出链接添加target =“_ blank”
我需要一些帮助来创建jquery脚本:)
我的HTML上有一些像这样的链接。
Google Home Home Contact Us
现在我希望jQuery检查我页面上的所有链接。 如果该链接在我的服务器之外(我的服务器是gusdecool.com
)。 然后添加target="_blank"
。 结果将是这样的
Google Home Home Contact Us
假设所有外部链接都以http://开头,你可以这样做:
$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');
$('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if (!a.test(this.href)) { $(this).attr("target","_blank"); } });
这是来自css-tricks.com,似乎工作得很好。
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');
当然,只有当所有外部链接都以http协议开头时,这才有效。 您应该调整此代码以满足您的需求(例如没有协议或不同协议的链接)。
更新:
$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])') .add('a[href^=www]:not([href^=www.gusdecool.com])') .attr('target','_blank');
它选择所有具有以网页地址(带或不带协议)开头的href
属性a
元素,并且不指向您网站的地址并将其target
属性更改为_blank
。
如果你有一个子域,这个函数似乎更容易:
$('a').attr('target', function() { if(this.host == location.host) return '_self' else return '_blank' });
jQuery(document).ready(function(){ target_luar(); }); function target_luar(){ try{ if(top.location != location) { jQuery("a[href^='http']") .not("[href*='"+location.host+"']") .attr('target','_blank'); } } catch(err) { } }
演示: 演示jQuery外部链接
在新窗口中打开外部链接的全局function:
$(function(){ // document ready $("a").filter(function () { return this.hostname && this.hostname !== location.hostname; }).each(function () { $(this).attr({ target: "_blank", title: "Visit " + this.href + " (click to open in a new window)" }); }); });
您可以使用jQuery的$ .each函数迭代所有Anchor标记,执行所需的检查并使用$(this).attr(“target”,“_ blank”)设置“target”属性;
示例(未测试但应该有效):
$('a').each(function(index) { var link = $(this).attr("href"); if(link.substring(0,7) == "http://") $(this).attr("target", "_blank"); });
夏嘉曦。
把它们放在一起我们得到以下结果..等待全部加载,只选择以http或https开头的链接,检查链接是指向同一域(内部)还是另一个域(外部),如果匹配则添加适当的目标发现..
$(window).load(function() { $('a[href^="http"]').attr('target', function() { if(this.host == location.host) return '_self' else return '_blank' }); });
你可以使用filter
–
$("a").filter(function () { return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 }).attr("target","_blank");
检查每个linkobject $(link).attr(“href”),如果以http://开头,那么它是一个外向链接(?)。 然后分配.attr(“target”,“_ blank”)。
$(a).function(){ if($(this).attr("href").substring(0,3) == "http" && ){ $(this).attr("target", "_blank"); } };
希望这可以帮助。
这是一个使用原始JS(而不是jQuery)演示答案的小提琴: http : //jsfiddle.net/Xwqmm/
这是代码:
var as = document.getElementsByTagName('a'); var re = /^https?:\/\/([^\/]*)\//; for (var i = 0, l = as.length; i < l; i++) { var href = as[i].href; var matches = href.match(re); if (matches[1] && matches[1] != "gusdecool.com") { as[i].setAttribute("target","_blank"); } }
尝试:
$('a[href^="http://"]') .not('a[href*='+ location.hostname +']') .attr('target','_blank');