获取链接参数

1、url paramter
//获取多个、若有重复则取最后一个 
var getArgs=function() {//get url querystring 
    var params=document.location.search,reg=/(?:^\?|&)(.*?)=(.*?)(?=&|$)/g,temp,args={}; 
    while((temp=reg.exec(params))!=null) args[temp[1]]=decodeURIComponent(temp[2]); 
    return args; 
}; 
//只取一个: 
var queryString=function(key){ 
    return (document.location.search.match(new RegExp("(?:^\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1]; 
} 

2、script paramter

//获取多个参数 
var getScriptArgs=function(){
    var scripts=document.getElementsByTagName("script"), 
    script=scripts[scripts.length-1],//因为当前dom加载时后面的script标签还未加载,所以最后一个就是当前的script 
    src=script.src, 
    reg=/(?:\?|&)(.*?)=(.*?)(?=&|$)/g, 
    temp,res={}; 
    while((temp=reg.exec(src))!=null) res[temp[1]]=decodeURIComponent(temp[2]); 
    return res; 
}; 
var args=getScriptArgs(); 
alert(args.a+" | "+args.b+" | "+args.c); 
//<script type="text/javascript" src="js1.js?a=abc&b=汉字&c=123"></script> 

//获取单个参数 
var getScriptArg=function(key){
    var scripts=document.getElementsByTagName("script"), 
    script=scripts[scripts.length-1], 
    src=script.src; 
    return (src.match(new RegExp("(?:\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1]; 
}; 
alert(getScriptArg("c"));

 

posted @ 2016-03-15 14:44  圣耀  阅读(406)  评论(0编辑  收藏  举报