在没有jQuery的新选项卡中打开外部链接 [英] Open external links in a new tab without jQuery

查看:148
本文介绍了在没有jQuery的新选项卡中打开外部链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the best way to open all external links (URLs that don't match the current domain) in a new tab using JavaScript, without using jQuery?

这里是我目前正在使用的jQuery:

Here's the jQuery I'm current using:

// 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;
    }
});


推荐答案

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

这篇关于在没有jQuery的新选项卡中打开外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆