2013-06-12 39 views
3

我有下面的代碼,將增加target="_blank"所有鏈接:添加目標=「_空白」的所有鏈接,但內部站點鏈接

$(function() { 
    $("a[href^='http://']").attr("target","_blank"); 
}); 

如何將我重新寫上面的代碼爲目標,除了所有鏈接內部鏈接。

IE:

http://www.my-site.com/ =內部鏈接

http://www.other-site.com/ =外部鏈接

此外,我怎麼會針對不以http://開始,但不是內部的任何鏈接?

我正在尋找一個jQuery解決方案。

+0

你想要以'http://'開頭的目標是什麼樣的外部鏈接?只是'https://'? – Marcel

+0

@Marcel - 我有幾個鏈接從'ftp'開始,但實際上我可以手動添加這些鏈接。除此之外是'https://' – L84

回答

6

剛剛鏈中的選擇:

$("a[href^='http']:not([href^='http://www.mysite.com'])").attr("target","_blank"); 

這將選擇http(所以沒有相對的內部)開始,但不與http://www.mysite.com開始(所以不是絕對內部其一)的所有鏈接。

+0

這很好,很簡潔。 – Marcel

+0

使用此解決方案可能會出現性能問題。 – Ohgodwhy

+0

對於支持這些CSS3選擇器的現代瀏覽器來說,並不是真的,瀏覽器本地處理這些選擇,而對於較老的瀏覽器,Sizzle選擇器引擎不僅能在現代計算機上以毫秒爲單位執行這種一次搜索。無論如何,它不會比Marcel的解決方案慢很多,它會循環更多的元素並將字符串搜索應用於所有元素。 –

4

我在使用jQuery時使用了以下的JavaScript代碼。它還爲外部鏈接添加了一個類,並在Google Analytics中包含跟蹤外發鏈接。如果您不使用Google Analytics,請將其刪除。

如果您不希望它擊中頁面上的所有鏈接,例如$("#main a[href^=http]"),則可以使用更具體的選擇器。

$("a[href^=http]") 
    .each(function(){ 
    // this part checks if the link is external 
    if (this.href.indexOf(location.hostname) == -1){ 
     // add a class for external links 
     $(this).addClass("ext") 
     // make the link open in a new tab/window 
     .attr({ "target":"_blank", "rel":"external" }) 
     // track clicks of external links if you use Google Analytics 
     .click(function(){ 
      _gaq.push(["_trackEvent", "Outgoing link", "click", $(this).attr("href")]); 
     }); 
    } 
    }); 
+0

我唯一的建議是在執行比較時使用.toLowerCase()。 – Ohgodwhy

相關問題