打开除域之外的新选项卡中打开的所有外部链接

我正在尝试在新窗口中打开网站上的所有外部链接。 但是,该网站有2个版本。 例如商店和主要网站。 因此,在主站点上,我们可能会有链接到http://store.site.com 。

我在这里有一些代码可以让我在新窗口中打开所有外部链接。 但是,我希望能够排除某些域名。 就像我上面提到的那个。

这是代码:

$(document).ready(function() { $("a[href^=http]").each(function(){ if(this.href.indexOf(location.hostname) == -1) { $(this).attr({ target: "_blank", title: "Opens in a new window" }); } }) }); 

我是JS / Jquery的新手,所以很多信息都很棒。

要以编程方式触发点击,您可以执行以下操作:

 $(document).ready(function() { $("a[href^=http]").each(function(){ // NEW - excluded domains list var excludes = [ 'excludeddomain1.com', 'excludeddomain2.com', 'excluded.subdomain.com' ]; for(i=0; i 

您是否可以编辑HTML以获得更好的钩子,可能是点击事件? 如果我需要在内部或外部之间分隔某些链接,我将在HTML元素上应用rel值。

  Link 

然后在你的JavaScript中

  $('a[rel="external"]').click( function(event) { event.stopPropagation(); window.open( $(this).attr('href') ); return false; }); 

编辑:看到你已经有很多链接,这个怎么样..

  var a = new RegExp('http:\/\/store.blah.com'); $('a').each(function() { if(a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } }); 

我想我会这样做:

  $(document).ready(function() { $("a[href^=http]").each(function(){ if(this.href.indexOf(location.hostname) == -1 && this.href.indexOf("store.domain.com") == -1 && this.href.indexOf("other.domain.rule") == -1) { $(this).attr({ target: "_blank", title: "Opens in a new window" }); } }) }); 

这是一种手动但是,如果你不想处理拆分字符串和数组,这就是解决方案。 我相信这会有所帮助。

编辑:除此之外,您还可以使用techfoobar的解决方案来触发链接点击。 这将有助于您的网站性能。

与techfoobar的回复相同,您可以构建一个应该在同一窗口中打开的域列表。 您可以使用常规表达式以更强大的方式执行此操作。 如果您只是直接执行indexOf()检查,您将跳过具有匹配子域但不匹配域的链接,但如果要在href字符串中的任何位置匹配名称,则可以省略’$’。

此实现应该按照您的需要执行,并且对您需要的代码进行最少的修改。

 $(document).ready(function() { //populate this list with whatever domain names you want, the //$ sign matches the end of the string, only top level domains are affected var whiteList = [/google.com\/$/, /stackoverflow.com\/$/]; $("a[href^=http]").each(function(){ if(this.href.indexOf(location.hostname) == -1) { //check if the href of the current link matches any of our patterns var href = this.href; if(whiteList.filter(function(x){return x.test(href)}).length == 0) { $(this).attr({ target: "_blank", title: "Opens in a new window" }); } } }) }); 

在此示例中,所有前往google.com和stackoverflow.com的链接也将在现有页面中打开。

如果您宁愿在身体上使用事件处理程序而不是更改dom,我推荐这样的东西……

  // open external links in a new tab $('body').on('click','a',function(){ var $a = $(this); var href = $a.attr('href'); if (href.indexOf('/') == 0) return; // ignore relative links var target = $a.attr('target') || ""; if (target.length > 0) return; // ignore links with a target attribute already window.open(href, '_blank'); // open external links in a new tab return false; }); 

这将使用PHP为所有外部域提供技巧

 $(document).ready(function() { $("a[href^=http]").each(function(){ // NEW - excluded domains list var excludes = [ '' ]; for(i=0; i