jQuery add target=“_blank” for outgoing link

后端 未结 15 1740
滥情空心
滥情空心 2020-12-13 04:01

I need some help to create jquery script :)
I have some of link like this on my HTML.

Google


        
相关标签:
15条回答
  • 2020-12-13 04:44
    $('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');
    

    Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).

    UPDATE :

    $('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
        .add('a[href^=www]:not([href^=www.gusdecool.com])')
            .attr('target','_blank');
    

    It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.

    0 讨论(0)
  • 2020-12-13 04:45
    $('a').each(function() {
       var a = new RegExp('/' + window.location.host + '/');
       if (!a.test(this.href)) {
          $(this).attr("target","_blank");
       }
    });
    

    This was from css-tricks.com, seems to work pretty well.

    0 讨论(0)
  • 2020-12-13 04:45

    Global function to open external links in a new window:

    $(function(){ // document ready
    
        $("a").filter(function () {
            return this.hostname && this.hostname !== location.hostname;
        }).each(function () {
            $(this).attr({
                target: "_blank",
                title: "Visit " + this.href + " (click to open in a new window)"
            });
        });
    
    });
    
    0 讨论(0)
  • 2020-12-13 04:47

    This function seems to be easier if you have a subdomain:

    $('a').attr('target', function() {
      if(this.host == location.host) return '_self'
      else return '_blank'
    });
    
    0 讨论(0)
  • 2020-12-13 04:47

    Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").

    $(a).function(){
        if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
           $(this).attr("target", "_blank"); 
        }
    };
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-13 04:47

    This is such a brilliant site I learned so much from it :

    If you do it this way you do not need to worry about http or https (handy while developing)

    $('a[href^="http"]')
            .not('a[href*='+ location.hostname +']')
            .attr('target','_blank');
    
    
    0 讨论(0)
提交回复
热议问题