微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试在新窗口中打开网站上的所有外部链接.但是,该网站有2个版本.例如商店和主要网站.因此,在主站点上,我们可能会有链接,例如 http://store.site.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的新手,所以很多信息都很棒.

解决方法

要以编程方式触发点击,您可以执行以下操作:
$(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
      }
   })
});

原文地址:https://www.jb51.cc/js/158246.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐