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)
| 归档时间: |
|
| 查看次数: |
6978 次 |
| 最近记录: |