打开除域之外的新选项卡中打开的所有外部链接 [英] Open all external links open in a new tab apart from a domain
问题描述
我正在尝试在新窗口中打开网站上的所有外部链接。但是,该网站有2个版本。例如商店和主要网站。因此,在主站点上,我们可能会有关于 http://store.site.com 的链接。 / p>
我这里有一些代码可以让我在新窗口中打开所有外部链接。但是,我希望能够排除某些域名。就像我上面提到的那样。
这是代码:
$(document).ready(function(){
$(a [href ^ = http])。each(function(){
if(this.href.indexOf(location) .hostname)== -1){
$(this).attr({
target:_ blank,
title:在新窗口中打开
}) ;
}
})
});
我是JS / Jquery的新手,所以很多信息都很棒。
为了以编程方式触发点击,您可以执行以下操作:
$(document).ready(function(){
$(a [href ^ = http])。each(function(){
//新 - 排除域名列表
var excludes = [
'edleddomain1.com',
'edleddomain2.com',
'edled.subdomain.com'
$;
for(i = 0; i< excludes.length; i ++){
if(this.href.indexOf(excludes [i])!= -1){
return true; //使用下一个链接继续each()
}
}
if(this.href.indexOf(location.hostname)== -1){
//附加一个do-nothing事件处理程序,以确保我们可以触发此链接上的点击
$(this).click(function(){return true;});
$(this).attr({
target:_ blank,
title:在新窗口中打开
});
$(this).click(); //触发它
}
})
});
I'm trying to open all external links on the site in a new window. However on there are 2 versions of the site. e.g a store and the main site. So on the main site we might have links that go to http://store.site.com for example.
I've got some code here which will allow me to open all the external links in a new window. However I'd like to be able to exclude certain domains. Like the one I've mentioned above.
Here is the code:
$(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"
});
}
})
});
I'm new to JS / Jquery so as much information would be brilliant.
For triggering the clicks programmatically, you can do something like:
$(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
}
})
});
这篇关于打开除域之外的新选项卡中打开的所有外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!