Test if links are external with jQuery / javascript?

后端 未结 13 1336
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for \"http\". I could just as
13条回答
  •  抹茶落季
    2020-11-28 05:35

    For those interested, I did a ternary version of the if block with a check to see what classes the element has and what class gets attached.

    $(document).ready(function () {
        $("a").click(function (e) {
    
            var hostname = new RegExp(location.host);
            var url = $(this).attr("href");
    
            hostname.test(url) ?
            $(this).addClass('local') :
            url.slice(0, 1) == "/" && url.slice(-1) == "/" ?
            $(this).addClass('localpage') :
            url.slice(0, 1) == "#" ?
            $(this).addClass('anchor') :
            $(this).addClass('external');
    
            var classes = $(this).attr("class");
    
            console.log("Link classes: " + classes);
    
            $(this).hasClass("external") ? googleAnalytics(url) :
            $(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local");
    
        });
    });
    

    The google analytics bit can be ignored but this is where you'd probably like to do something with the url now that you know what type of link it is. Just add code inside the ternary block. If you only want to check 1 type of link then replace the ternaries with an if statement instead.

    Edited to add in an issue I came across. Some of my hrefs were "/Courses/" like so. I did a check for a localpage which checks if there is a slash at the start and end of the href. Although just checking for a '/' at the start is probably sufficient.

提交回复
热议问题