我正在尝试在新窗口中打开网站上的所有外部链接.但是,该网站有2个版本.例如商店和主要网站.因此,在主站点上,我们可能会有链接,例如
http://store.site.com.
我在这里有一些代码可以让我在新窗口中打开所有外部链接.但是,我希望能够排除某些域名.就像我上面提到的那个.
这是代码:
@H_301_6@$(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的新手,所以很多信息都很棒.
解决方法
要以编程方式触发点击,您可以执行以下操作:
@H_301_6@$(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
}
})
});