Home > Web Front-end > JS Tutorial > body text

How to Retrieve and Use a URL Query String Parameter with jQuery?

Susan Sarandon
Release: 2024-11-25 00:54:13
Original
710 people have browsed it

How to Retrieve and Use a URL Query String Parameter with jQuery?

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;
}
Copy after login

Next, use the getUrlVars() function to extract the "location" value:

var locationValue = getUrlVars()['location'];
Copy after login

Now, you can utilize the extracted value in your jQuery code:

$('html,body').animate({ scrollTop: $('#div#' + locationValue).offset().top }, 500);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template