在没有jQuery的新选项卡中打开外部链接

时间:2012-10-20 11:29:12

标签: javascript hyperlink

在不使用jQuery的情况下,使用JavaScript在新标签页中打开所有外部链接(与当前域不匹配的URL)的最佳方法是什么?

这是我目前正在使用的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;
    }
});

4 个答案:

答案 0 :(得分:17)

Pure 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();

答案 1 :(得分:0)

向标记添加target =“_ blank”。您可以在onload事件期间在预处理器(例如PHP)或JS中执行此操作。

答案 2 :(得分:0)

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

此脚本应该适合您。

更新:试试这个小提琴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';
        }
      }
    };

答案 3 :(得分:0)

links 属性返回文档中所有 <area><a> 元素的集合,并带有 href 属性的值。

   var links = document.links;
    for(var i = 0; i < links.length; i++) {
      if (links[i].hostname != window.location.hostname) {
        links[i].target = '_blank';
      } 
    }

https://developer.mozilla.org/en-US/docs/Web/API/Document/links

相关问题