jQuery add target=“_blank” for outgoing link

后端 未结 15 1803
滥情空心
滥情空心 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: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'
        });
    });
    

提交回复
热议问题