虽然可以通过get方式提交post表单等方式来动态修改url,但如果多个按钮能并行提交时,写多个大体相同,又有些细节差异的表单,难免有些不妥,因此,想到了通过JS来动态的修改url,来实现对url的增删查改。
1 <script>
2
3 var LG=(function(lg){
4 var objURL=function(url){
5 this.ourl=url||window.location.href;
6 this.href="";//?前面部分
7 this.params={};//url参数对象
8 this.jing="";//#及后面部分
9 this.init();
10 }
11 //分析url,得到?前面存入this.href,参数解析为this.params对象,#号及后面存入this.jing
12 objURL.prototype.init=function(){
13 var str=this.ourl;
14 var index=str.indexOf("#");
15 if(index>0){
16 this.jing=str.substr(index);
17 str=str.substring(0,index);
18 }
19 index=str.indexOf("?");
20 if(index>0){
21 this.href=str.substring(0,index);
22 str=str.substr(index+1);
23 var parts=str.split("&");
24 for(var i=0;i<parts.length;i++){
25 var kv=parts[i].split("=");
26 this.params[kv[0]]=kv[1];
27 }
28 }
29 else{
30 this.href=this.ourl;
31 this.params={};
32 }
33 }
34 //只是修改this.params
35 objURL.prototype.set=function(key,val){
36 this.params[key]=val;
37 }
38 //只是设置this.params
39 objURL.prototype.remove=function(key){
40 this.params[key]=undefined;
41 }
42 //根据三部分组成操作后的url
43 objURL.prototype.url=function(){
44 var strurl=this.href;
45 var objps=[];//这里用数组组织,再做join操作
46 for(var k in this.params){
47 if(this.params[k]){
48 objps.push(k+"="+this.params[k]);
49 }
50 }
51 if(objps.length>0){
52 strurl+="?"+objps.join("&");
53 }
54 if(this.jing.length>0){
55 strurl+=this.jing;
56 }
57 return strurl;
58 }
59 //得到参数值
60 objURL.prototype.get=function(key){
61 return this.params[key];
62 }
63 lg.URL=objURL;
64 return lg;
65 }(LG||{}));
66
67
68 var myurl=new LG.URL(window.location.href);
69 myurl.remove("b"); //删除了b
70 alert(myurl.get ("a"));//取参数a的值,这里得到1
71 myurl.set("a",23); //修改a的值为23
72 alert (myurl.url());
73 </script>
相关文章:
-
2022-12-23
-
2022-12-23
-
2022-12-23
-
2022-12-23
-
2022-12-23
-
2021-11-19