Using jQuery to check if a link is internal or external

后端 未结 8 879
南旧
南旧 2020-12-29 09:29

I want to write a script which can determine whether a link is internal or external. This is simple from my perspective, all internal links are relative, so they start with

8条回答
  •  隐瞒了意图╮
    2020-12-29 10:12

    I'm using WordPress for my CMS, and so most (if not all) of my internal links start with "http". I found a pretty interesting solution here: http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site

    In case that site is down, it basically boils down to this selector (I modified it a bit):

    $( 'a[href^="//"],a[href^="http"]' )
        .not( '[href*="' + window.location.hostname + '"]' )
    ;
    

    Note that this selector will not be the fastest according to the jQuery docs.

提交回复
热议问题