在没有 jQuery 的新选项卡中打开外部链接 [英] Open external links in a new tab without jQuery
本文介绍了在没有 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屋!
查看全文