打开所有链接不是我的网站的一部分,在新的窗口与jquery

Open all links not part of my website in new window with jquery

本文关键字:一部分 窗口 jquery 网站 链接 我的      更新时间:2023-09-26

我不知道我必须在'???,让它检查这个网站是不是我的地址。这是否也适用于google adsense广告(只是好奇,但不重要)?

我正在考虑使用像'not'这样的逻辑运算符。所以它会检查是否不是我的网站?那么??是我的网站吗?

$j(!a[href=???]).click(function(){
                window.open(this.href, "target=_blank");
                return false;
            });

试试这个:

$j('a')
    .not('[name^="http://your.domain.com/"]')
    .attr('target', '_blank');

我以前的修复只适用于如果所有的url都是绝对的,这是一个糟糕的假设。试试这个:

$j('a[name^="http:"], a[name^="https:"]')
    .not('[name^="http://your.domain.com/"]')
    .attr('target', '_blank');

这个新版本跳过所有的相对url。如果你所有的站点内url都是相对的(即不以https?:开头),你可以跳过对.not的调用。

运行像$( 'a' )这样的东西将通过每个A元素循环-您只能在实际点击时担心它。此外,你可以运行相对url是你的网站,绝对url是别人的。

$( document ).on( 'click', 'a', function( event ){
  var $a = $( this );
  // test for anything like `http://` or '//whatever' or 'ftp://'
  if ( /^'w+?':?'/'//.test( $a.attr( 'href' ) ) ){
    // since this runs before the event is propagated,
    // adding it now will still work
    $a.prop( 'target', '_blank' );
  }
});

演示:http://jsfiddle.net/danheberden/3bnk9/

或者你可以使用window.open:

$( document ).on( 'click', 'a', function( event ){
  var href = $( this ).attr( 'href' );
  // test for anything like `http://` or '//whatever' or 'ftp://'
  if ( /^'w+?':?'/'//.test( href ) ){
    // dont follow the link here
    event.preventDefault();
    //  open the page
    window.open( href, '_blank' );
  }
});

演示:http://jsfiddle.net/danheberden/NcKdh/

您可以创建一个类来实现:

// Outbound Links
var outLinks = function() { $('a[@class*=out]').click( function(){ this.target = '_blank'; } ); }
$(document).ready(outLinks);

然后你所需要做的就是添加"out"类到任何链接,它将打开一个新窗口。

或任何以http://

开头的链接
$('a[href^="http://"]').prop("target", "_blank");

如何:

$j('a').live('click', function(){
  if(this.href.indexOf('yourwebsite.com') == -1) {
    window.open(this.href, "target=_blank");
    return false;
  }
});

这也可以通过一个正则表达式来改进,这样它就不会捕获像http://someothersite.com/yourwebsite.com/这样的url,但这是一个边缘情况。