jQuery add target=“_blank” for outgoing link

后端 未结 15 1737
滥情空心
滥情空心 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:31

    assuming that all external links will start with http:// you could do this:

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

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

    Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..

    $(window).load(function() {
        $('a[href^="http"]').attr('target', function() {
          if(this.host == location.host) return '_self'
          else return '_blank'
        });
    });
    
    0 讨论(0)
  • 2020-12-13 04:33

    You can see all external link whith http and https

    
    jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
      
        console.log(jQuery(this).attr('href'))
    });
    
    

    And you can add _blank like this

    jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
    
    0 讨论(0)
  • 2020-12-13 04:34

    You could use filter -

    $("a").filter(function () {
        return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 
    }).attr("target","_blank");  
    
    0 讨论(0)
  • 2020-12-13 04:38

    Try:

    $('a[href^="http://"]')
            .not('a[href*='+ location.hostname +']')
            .attr('target','_blank');
    
    0 讨论(0)
  • 2020-12-13 04:40
    jQuery(document).ready(function(){
        target_luar();
    });    
    function target_luar(){
        try{
            if(top.location != location) {
                jQuery("a[href^='http']")
                  .not("[href*='"+location.host+"']")
                  .attr('target','_blank');
            }
        } catch(err) { }
    }
    

    Demo : Demo jQuery External Link

    0 讨论(0)
提交回复
热议问题