This article mainly introduces javascriptjquery's method for obtaining url parameters in the address bar. If you need it, refer to it, we hope it will be helpful for you to use jquery to obtain the url and use jquery to obtain url parameters. This is a frequently used operation.
1. jquery is easy to get the url. The Code is as follows:
The Code is as follows:
Window. location. href;
In fact, it only uses the basic window object of javascript and does not use jquery knowledge.
2. It is complicated for jquery to obtain url parameters. Regular Expressions are needed, so it is important to learn javascript Regular Expressions well.
First, let's take a look at how javascript can be used to obtain a parameter in a url.
The Code is as follows:
Function getUrlParam (name)
{
Var reg = new RegExp ("(^ | &)" + name + "= ([^ &] *) (& | $ )"); // construct a regular expression object containing the target parameter
Var r = window. location. search. substr (1). match (reg); // match the target parameter
If (r! = Null) return unescape (r [2]); return null; // return the parameter value
}
Pass the parameter name in the url through this function to get the parameter value. For example, if the url is
Http://www.xxx.loc/admin/write-post.php? Cid = 79
To obtain the cid value, we can write it as follows:
The Code is as follows:
GetUrlParam ('cid ');
After understanding how javascript gets url parameters, we can use this method to expand a method for jquery to get url parameters through jquery.
Extension of the getUrlParam () method for jquery
The Code is as follows:
(Function ($ ){
$. GetUrlParam
= Function (name)
{
Var reg
= New RegExp ("(^ | &)" +
Name + "= ([^ &] *) (& | $ )");
Var r
= Window. location. search. substr (1). match (reg );
If (r! = Null) return unescape (r [2]); return null;
}
}) (JQuery );
After this method is extended for jquery, we can use the following method to obtain the value of a parameter.
The Code is as follows:
$. GetUrlParam ('cid ');