This article mainly introduces how to obtain url parameters through js analysis url? In the previous section, # And later sections, you can check the code. The main idea is to parse url parameters into js objects, it is convenient to add, delete, modify, and query operations ~, Take notes here.
The Code is as follows:
Var LG = (function (lg ){
Var objURL = function (url ){
This. ourl = url | window. location. href;
This. href = "";//? Previous section
This. params = {}; // url parameter object
This. jing = ""; // # And later sections
This. init ();
}
// Analyze the url? This. href is saved before, and the parameter is parsed as this. params object.
ObjURL. prototype. init = function (){
Var str = this. ourl;
Var index = str. indexOf ("#");
If (index> 0 ){
This. jing = str. substr (index );
Str = str. substring (0, index );
}
Index = str. indexOf ("? ");
If (index> 0 ){
This. href = str. substring (0, index );
Str = str. substr (index + 1 );
Var parts = str. split ("&");
For (var I = 0; I Var kv = parts [0]. split ("= ");
This. params [kv [0] = kv [1];
}
}
Else {
This. href = this. ourl;
This. params = {};
}
}
// Only modify this. params
ObjURL. prototype. set = function (key, val ){
This. params [key] = val;
}
// Just set this. params
ObjURL. prototype. remove = function (key ){
This. params [key] = undefined;
}
// Url after the three-part Operation
ObjURL. prototype. url = function (){
Var strurl = this. href;
Var objps = []; // The array is used for organizing and then performing the join operation.
For (var k in this. params ){
If (this. params [k]) {
Objps. push (k + "=" + this. params [k]);
}
}
If (objps. length> 0 ){
Strurl + = "? "+ Objps. join ("&");
}
If (this. jing. length> 0 ){
Strurl + = this. jing;
}
Return strurl;
}
// Obtain the parameter value
ObjURL. prototype. get = function (key ){
Return this. params [key];
}
Lg. URL = objURL;
Return lg;
} (LG | {}));
LG is just the namespace of my personal common JS. Call:
The Code is as follows:
Var myurl = new LG. URL ("http://www.baidu.com? A = 1 ");
Myurl. set ("B", "hello"); // added B = hello
Alert (myurl. url ());
Myurl. remove ("B"); // deleted B
Alert (myurl. get ("a"); // obtain the value of parameter a. Here, 1 is obtained.
Myurl. set ("a", 23); // modify the value of a to 23.
Alert (myurl. url ());