CodeIt is very simple. The main idea is to parse the URL parameter into a JS object and then add, delete, modify, and query operations ~, Take notes here.
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 to get? 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 <parts. length; I ++ ){ VaR KV = parts [0]. Split ("=" ); This . Params [kV [0] = kV [1 ] ;}} Else { This . Href = This . Ourl; This . Params = {};}} // Just 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 parts Objurl. Prototype. url = Function (){ VaR Strurl = This . Href; VaR Objps = []; // Here we use arrays to organize and then perform 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:
var myurl = New LG. URL ("http://www.baidu.com? A = 1 "); myurl. set ( "B", "hello"); // added B = Hello alert ( myurl . URL (); myurl. remove ( "B"); /// B alert (myurl. get ( "A"); /// take the value of parameter A. Here we get 1 myurl . set ( "A", 23); /// modify the value of a to 23 alert ( myurl . URL ();