javascript – 打开除域之外的新选项卡中打开的所有外部链接

前端之家收集整理的这篇文章主要介绍了javascript – 打开除域之外的新选项卡中打开的所有外部链接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在新窗口中打开网站上的所有外部链接.但是,该网站有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 } }) });

猜你在找的JavaScript相关文章