簡體   English   中英

使用jquery在新窗口中打開不屬於我的網站的所有鏈接

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

我不確定我必須在“ ???”中輸入什么 以便檢查該網站是否是我的地址。 這也適用於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都是絕對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,但這是一個極端的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM