Using jQuery to check if a link is internal or external

后端 未结 8 881
南旧
南旧 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:16

    You could use the attribute^=value syntax to find hrefs that start with http or /:

    $("a[href^='http']") // external
    
    $("a[href^='/']") // internal
    

    Here's a better solution: You can add $('a:external') and $('a:internal') selectors to jQuery with the plugin code below. Any URL that begins http://, https://, or whatever:// is considered external.

        $.expr[':'].external = function (a) {
            var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//;
            var href = $(a).attr('href');
            return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1;
        };
    
        $.expr[':'].internal = function (a) {
            return $(a).attr('href') !== undefined && !$.expr[':'].external(a);
        };
    
    0 讨论(0)
  • 2020-12-29 10:28

    I think the simple and less headaches approach for this is not to use pure javascript or jQuery, but combine it with html instead and then check if the clicked link containing your base site's url. It will work for any type of base url (eg.: example.com, example.com/site). If you need for dynamic value, then you just need to set the value using your preferred server side programming language, such as PHP, asp, java etc.

    Here is an example:

    HTML

    <!--Create a hidden input containing your base site's url.-->
    <input type="hidden" id="sitedomain" value="example.com/site"/>
    

    jQuery

    $(".elem").on("click", function(e){
      if($(this).closest("a").length) {
      var url = $(this).attr("href");
      var sitedomain = $("#sitedomain").val();
    
      if(url.indexOf(sitedomain) > -1) {
        alert("Internal");
      } else {
        alert("External");
      }
     }
    });
    
    0 讨论(0)
提交回复
热议问题