Home  >  Article  >  Web Front-end  >  javascript Get url parameters and get url parameter function code in script tag_javascript skills

javascript Get url parameters and get url parameter function code in script tag_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:36:061732browse

url paramter:

Copy code The code is as follows:

//lastest:
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;
};
//Just take one:
var queryString=function(key){
return (document.location.search.match(new RegExp("(?:^\? |&)" key "=(.*?)(?=&|$)"))||['',null])[1];
}
var args=getArgs();
alert(args.name " | " args.sex " | " args.age);
//Test link: test getQueryString< /a>




script paramter:
Copy code The code is as follows:

var getScriptArgs=function(){//Get multiple parameters
var scripts=document.getElementsByTagName("script"),
script=scripts[scripts.length -1], //Because the following script tags have not been loaded when the current dom is loaded, the last one is the current 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);
//If the above js is in the script of js1.js

var getScriptArg=function(key){//Get a single parameter
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: Don’t use it in the method Call the method in the method, otherwise you may always get the parameters of the last js file. To use it in the method, please save it with a variable first and get it directly in the method.
Statement:
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