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

Ale*_*ust 8 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;
    }
});
Run Code Online (Sandbox Code Playgroud)

eye*_*hUp 19

纯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();
Run Code Online (Sandbox Code Playgroud)