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

前端 未结 4 1201
没有蜡笔的小新
没有蜡笔的小新 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

    click here
    

    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;
      }
    }
    

提交回复
热议问题