我正在尝试在新窗口中打开网站上的所有外部链接。然而,该网站有两个版本,例如商店和主网站。例如,在主站点上,我们可能有指向http://store.example.com的链接。
我这里有一些代码,可以让我在一个新窗口中打开所有的外部链接。但是,我希望能够排除某些域。就像我上面提到的那个。
代码如下:
$(document).ready(function() {
$("a[href^=http]").each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
}
})
});
我是JS / jQuery的新手,所以任何其他信息都会很有用。
发布于 2012-08-22 18:44:06
为了以编程方式触发点击,您可以执行以下操作:
$(document).ready(function() {
$("a[href^=http]").each(function(){
// NEW - excluded domains list
var excludes = [
'excludeddomain1.com',
'excludeddomain2.com',
'excluded.subdomain.com'
];
for(i=0; i<excludes.length; i++) {
if(this.href.indexOf(excludes[i]) != -1) {
return true; // continue each() with next link
}
}
if(this.href.indexOf(location.hostname) == -1) {
// attach a do-nothing event handler to ensure we can 'trigger' a click on this link
$(this).click(function() { return true; });
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
$(this).click(); // trigger it
}
})
});
发布于 2019-05-14 03:23:02
如果你只是想要所有与你的域名不匹配的链接:
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++){
var a = all_links[i];
if(a.hostname != location.hostname) {
a.rel = 'noopener';
a.target = '_blank';
}
}
发布于 2012-08-22 18:44:54
您是否能够编辑HTML以获得更好的钩子来处理单击事件?如果我需要分隔内部或外部之间的某些链接,我将在HTML元素上应用rel值。
<a href="URL" rel="external">Link</a>
然后在你的javascript中
$('a[rel="external"]').click( function(event) {
event.stopPropagation();
window.open( $(this).attr('href') );
return false;
});
编辑:既然你已经有了一大堆链接,不如这样吧..
var a = new RegExp('http:\/\/store.blah.com');
$('a').each(function() {
if(a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
https://stackoverflow.com/questions/12071254
复制相似问题