在没有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();