url paramter:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->//lastest:var queryStrings=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];}var args=getArgs();alert(args.name+" | "+args.sex+" | "+args.age);//測試連結:<a href="?name=abc&sex=男&age=12">test getQueryString</a>
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);//假如上面的js是在這個js1.js的指令碼中<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"));
ps:不要在方法中調用此方法,否則可能始終擷取的是最後一個js的檔案的參數,要在方法中使用,請先放到js載入時就會執行的變數中 儲存