本文原理是使用正则表达式匹配location.search中的字符串。其中三个主要函数为 getQueryString()、getQueryStringByName(name)和getQueryStringByIndex(index)
三个主要方法:
方法
|
说明
|
getQueryString
|
获取QueryString的数组。
例如路径QueryStringDemo.html?id=5&type=1&flag=0
调用后返回["id=5", "type=1", "flag=0"]
|
getQueryStringByName
|
根据QueryString参数名称获取值
|
getQueryStringByIndex
|
根据QueryString参数索引获取值
|
//Get the array of QueryString
function getQueryString(){
var result = location.search.match(new RegExp("[?&][^?&] =[^?&] ","g"));
for(var i = 0; i < ; result.length; i ){
result[i] = result[i].substring(1);
}
return result;
}
//Get based on QueryString parameter name value
function getQueryStringByName(name){
var result = location.search.match(new RegExp("[?&]" name "=([^&] )","i"));
if(result == null || result.length < 1){
return "";
}
return result[1];
}
//According to QueryString parameter index Get value
function getQueryStringByIndex(index){
if(index == null){
return "";
}
var queryStringList = getQueryString();
if (index > ;= queryStringList.length){
return "";
}
var result = queryStringList[index];
var startIndex = result.indexOf("=") 1;
result = result.substring(startIndex);
return result;
}
Test page path: QueryStringDemo.html?id=5&type=1&flag=0
When the page loads:
Enter the name of the QueryString to be obtained in the text box after QueryString's name to obtain the corresponding value:
Enter the name of the QueryString to be obtained in the text box after QueryString's index Index to obtain the corresponding value (the index starts from 0):
In this way, you can easily obtain the value of QueryString in the page. Finally, the source code of the test page QueryStringDemo.html is attached:
pdf version download address