How to get the parameters of an href attribute of a link from the click event object

前端 未结 4 1183
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 16:37

Is there a simple way to get the parameters at the end of an href attribute of a clicked link using the click event object?

I have some jQuery code that looks like this:

相关标签:
4条回答
  • 2021-02-15 17:07

    Developing Sarfraz answer, given an anchor

    <a class="the_link" href="http://www.example.com/?a=1&date=2014-7-30&cat=all">click here</a>
    

    You can get the query params

    jQuery(document).ready(function($) {
      $('a.the_link').click(function(){    // when clicking on the link
        var href = $(this).attr('href');   // get the href of the anchor
        var params = get_params_from_href(href);
        console.log(params);               // OUTPUT: [a: "1", date: "2014-7-30", cat: "all"] 
        return false;                      // optional. do not navigate to href.
      });
    
      function get_params_from_href(href){
        var paramstr = href.split('?')[1];        // get what's after '?' in the href
        var paramsarr = paramstr.split('&');      // get all key-value items
        var params = Array();
        for (var i = 0; i < paramsarr.length; i++) {
            var tmparr = paramsarr[i].split('='); // split key from value
            params[tmparr[0]] = tmparr[1];        // sort them in a arr[key] = value way
        }
        return params;
      }
    }
    
    0 讨论(0)
  • 2021-02-15 17:11

    You can use the this.href method to read the link attribute:

    $('#pages').delegate("a", "click", function(e) {
       var str = this.href.split('?')[1];
    

    Example:

    str = 'friends.php?term=ma&p=2';
    console.log(str.split('?')[1]); // output: term=ma&p=2
    
    0 讨论(0)
  • 2021-02-15 17:14

    Yes, you can use the .search property of the link...

    alert( this.search );
    

    DEMO: http://jsfiddle.net/sHqmF/


    To get rid of the ?, just .slice() it...

    this.search.slice(1)
    

    DEMO: http://jsfiddle.net/sHqmF/1/

    0 讨论(0)
  • 2021-02-15 17:17

    jQuery itself doesn't support URL parsing. However there are lots of jQuery extensions available which do and make this an easy task. For example

    • https://github.com/allmarkedup/jQuery-URL-Parser

    With this extension you can do the following

    $('#pages').delegate("a", "click", function(e) {
      var href = $(this).attr('href');
      var url = $.url(href);
      var query = url.attr('query')
      ...
    });
    

    The extension itself supports much more than just the query string. You can use attr for practically every part of the url.

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