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:
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;
}
}
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
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/
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
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.