The code is very simple, the main idea is to parse the URL parameters to JS object, and then do add, delete, change, check the operation is very convenient ~, take notes here.
Copy Code code as follows:
var lg= (function (LG) {
var objurl=function (URL) {
this.ourl=url| | Window.location.href;
This.href= ""; the front part
This.params={};//url Parameter Object
This.jing= "";//#及后面部分
This.init ();
}
Parse the URL, get the front deposit this.href, the parameter resolves to the This.params object, #号及后面存入this. Jing
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<parts.length;i++) {
var kv=parts[0].split ("=");
THIS.PARAMS[KV[0]]=KV[1];
}
}
else{
This.href=this.ourl;
this.params={};
}
}
Just modify the 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;
}
Based on the three-part URL after the operation
Objurl.prototype.url=function () {
var strurl=this.href;
var objps=[];//here is organized with arrays, and then join operations
For (var k in this.params) {
if (This.params[k]) {
Objps.push (+ + "=" +this.params[k]);
}
}
if (objps.length>0) {
strurl+= "?" +objps.join ("&");
}
if (this.jing.length>0) {
strurl+=this.jing;
}
return strurl;
}
Get the value of the parameter
Objurl.prototype.get=function (key) {
return This.params[key];
}
Lg. Url=objurl;
return LG;
} (Lg| | {}));
LG is just my personal common JS namespace, without him. Call:
Copy Code code as follows:
var myurl=new LG. URL ("Http://www.baidu.com?a=1");
Myurl.set ("B", "Hello"); Added the B=hello
Alert (Myurl.url ());
Myurl.remove ("B"); deleted the B
Alert (Myurl.get ("a"))//Take the value of parameter A, here get 1
Myurl.set ("a", 23); Modify A to a value of 23
Alert (Myurl.url ());