Home > Web Front-end > JS Tutorial > JS to dynamically modify the url to add, delete, check and modify the url_javascript skills

JS to dynamically modify the url to add, delete, check and modify the url_javascript skills

WBOY
Release: 2016-05-16 16:36:53
Original
1257 people have browsed it

Although the URL can be dynamically modified by submitting the post form through get method, etc., if multiple buttons can be submitted in parallel, it will inevitably be inappropriate to write multiple forms that are roughly the same but have some differences in details. Therefore, I thought of Use JS to dynamically modify the URL to add, delete, check and modify the URL.

<script>

var LG=(function(lg){
var objURL=function(url){
this.ourl=url||window.location.href;
this.href="";//&#63;前面部分
this.params={};//url参数对象
this.jing="";//#及后面部分
this.init();
}
//分析url,得到&#63;前面存入this.href,参数解析为this.params对象,#号及后面存入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("&#63;");
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={};
}
}
//只是修改this.params
objURL.prototype.set=function(key,val){
this.params[key]=val;
}
//只是设置this.params
objURL.prototype.remove=function(key){
this.params[key]=undefined;
}
//根据三部分组成操作后的url
objURL.prototype.url=function(){
var strurl=this.href;
var objps=[];//这里用数组组织,再做join操作
for(var k in this.params){
if(this.params[k]){
objps.push(k+"="+this.params[k]);
}
}
if(objps.length>0){
strurl+="&#63;"+objps.join("&");
}
if(this.jing.length>0){
strurl+=this.jing;
}
return strurl;
}
//得到参数值
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"); //删除了b
alert(myurl.get ("a"));//取参数a的值,这里得到1
myurl.set("a",23); //修改a的值为23
alert (myurl.url());
</script>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template