[英]Open external links in a new tab without jQuery
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 的情况下使用 JavaScript 在新选项卡中打开所有外部链接(与当前域不匹配的 URL)的最佳方法是什么?
Here's the jQuery I'm current using:这是我目前使用的 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;
}
});
Pure JS:纯 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();
The links property returns a collection of all <area>
and <a>
elements in a document with a value for the href attribute. links属性返回文档中所有
<area>
和<a>
元素的集合,并具有 href 属性的值。
var links = document.links;
for(var i = 0; i < links.length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Document/links https://developer.mozilla.org/en-US/docs/Web/API/Document/links
Add a target="_blank" to the tag.将 target="_blank" 添加到标记中。 You could do that in the pre-processor (eg PHP) or in a JS during the onload event.
您可以在 onload 事件期间在预处理器(例如 PHP)或 JS 中执行此操作。
$("a[href^=http]").each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
}
})
This script should work for you.这个脚本应该适合你。
UPDATE: try this fiddle http://jsfiddle.net/sameerast/GuT2y/更新:试试这个小提琴http://jsfiddle.net/sameerast/GuT2y/
JS version JS版本
var externalLinks = function(){
var anchors = document.getElementsByTagName('a');
var length = anchors.length;
for(var i=0; i<length;i++){
var href = anchor[i].href;
if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){
return;
}
else{
anchor[i].target='_blank';
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.