2012-10-20 58 views
8

在不使用jQuery的情況下,使用JavaScript在新標籤頁中打開所有外部鏈接(與當前域不匹配的URL)的最佳方式是什麼?在沒有jQuery的情況下在新標籤頁中打開外部鏈接

這裏是jQuery的我用電流:

// Open external links in new tab 
$('a[href^=http]').click(function() { 
    var a = new RegExp('/' + window.location.host + '/'); 
    if (!a.test(this.href)) { 
     window.open(this.href); 
     return false; 
    } 
}); 

回答

16

純JS:

function externalLinks() { 
    for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) { 
    var b = c[a]; 
    b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank") 
    } 
} 
; 
externalLinks(); 
+0

完美,謝謝! – AlecRust

0

添加目標= 「_空白」 的標籤。您可以在預處理器(例如PHP)或onload事件中的JS中執行此操作。

+0

澄清問題。 – AlecRust

+0

您是否正在尋找一種方法在JavaScript中執行上述操作,但未使用jQuery?如果是這樣,你有任何其他庫,還是它必須是普通的JS? –

+0

平原JS如果可能的話。 – AlecRust

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

此腳本應該適合您。

UPDATE:試試這個小提琴http://jsfiddle.net/sameerast/GuT2y/

JS版本

var externalLinks = function(){ 
     var anchors = document.getElementsByTagName('a'); 
     var length = anchors.length; 
     for(var i=0; i<length;i++){ 
     var href = anchor[i].href; 
     if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){ 
      return; 
     } 
     else{ 
      anchor[i].target='_blank'; 
     } 
     } 
    }; 
+0

這不是使用jQuery的[.each()](http://api.jquery.com/jQuery.each/)函數嗎? – AlecRust

+0

它使用並添加目標=「_ blank」,然後用戶點擊它作爲新的標籤頁/窗口去鏈接 –

+0

就像我說的,你的解決方案不使用jQuery的.each()函數?我的問題指定不使用jQuery。 – AlecRust

相關問題