Retrieving Query String from URL Using jQuery
To extract the value of the "location" parameter from the URL provided ("http://www.mysite.co.uk/?location=mylocation1") and use it in jQuery code, follow these steps:
First, define a JavaScript function to parse the URL parameters:
function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }
Next, use the getUrlVars() function to extract the "location" value:
var locationValue = getUrlVars()['location'];
Now, you can utilize the extracted value in your jQuery code:
$('html,body').animate({ scrollTop: $('#div#' + locationValue).offset().top }, 500);
This will scroll the page to the element with the ID corresponding to the "location" value, as specified in the selector (e.g., "#div#mylocation1").
The above is the detailed content of How to Retrieve and Use a URL Query String Parameter with jQuery?. For more information, please follow other related articles on the PHP Chinese website!