JS to dynamically modify the url the url of the implementation of the addition and deletion

  • 2020-03-30 03:48:02
  • OfStack

Although it is possible to dynamically modify the url by submitting the post form through get, if multiple buttons can be submitted in parallel, it is inevitable that it is improper to write multiple forms that are roughly the same but with different details. Therefore, it is thought to modify the url dynamically through JS to realize the addition, deletion and modification of the url.


 <script>
 
 var LG=(function(lg){
   var objURL=function(url){
     this.ourl=url||window.location.href;
     this.href="";//The & # 63; The front part
     this.params={};//Url parameter object
     this.jing="";//# and the rest
     this.init();
   }
   //Analyze the url and get ? Save this.href in front, resolve the parameter as this.params object, and save this.jing after the # sign
   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[i].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;
   }
   //The resulting url is composed of three parts
   objURL.prototype.url=function(){
     var strurl=this.href;
     var objps=[];//I'm going to use an array here, and then I'm going to do join
     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;
   }
   //Get the parameter value
   objURL.prototype.get=function(key){
     return this.params[key];
   }  
   lg.URL=objURL;
   return lg;
 }(LG||{}));
 
     var myurl=new LG.URL(window.location.href);
     myurl.remove("b"); //Remove the b
     alert(myurl.get ("a"));//Take the value of parameter a, and you get 1 here
     myurl.set("a",23); //Modify the value of a to be 23
     alert (myurl.url());
 </script>


Related articles: