今天项目中遇到这个问题就是在Web前端根据URL的参数动态设置某一元素的值。
网上有很多这样的代码,无非是通过window.location.search、window.location或window.location.href获得到URl的地址,然后再解析它。
先说下这3个的区别,假设URL地址为:http://localhost:22606/WebSite3/Default3.aspx?a=1&b=1
window.location: http://localhost:22606/WebSite3/Default3.aspx?a=1&b=1
window.location.search: ?a=1&b=1
window.location.href: http://localhost:22606/WebSite3/Default3.aspx?a=1&b=1
现在就贴一段代码吧。
方法一:
代码
function getvalue(name)
{
var str=window.location.search;
if (str.indexOf(name)!=-1)
{
var pos_start=str.indexOf(name)+name.length+1;
var pos_end=str.indexOf("&",pos_start);
if (pos_end==-1)
{
return str.substring(pos_start);
}
else
{
return str.substring(pos_start,pos_end)
}
}
else
{
return "";
}
}
function getvalue(name)
{
var str=window.location.search;
if (str.indexOf(name)!=-1)
{
var pos_start=str.indexOf(name)+name.length+1;
var pos_end=str.indexOf("&",pos_start);
if (pos_end==-1)
{
return str.substring(pos_start);
}
else
{
return str.substring(pos_start,pos_end)
}
}
else
{
return "";
}
}
方法二:
代码
var URLParams = new Array();
var aParams = document.location.search.substr(1).split('&');
for (i=0; i < aParams.length; i++){
var aParam = aParams[i].split('=');
URLParams[aParam[0]] = aParam[1];
}
name=URLParams["name"];
var aParams = document.location.search.substr(1).split('&');
for (i=0; i < aParams.length; i++){
var aParam = aParams[i].split('=');
URLParams[aParam[0]] = aParam[1];
}
name=URLParams["name"];
alert(name)
方法三:
代码
Request = {
QueryString : function(item){
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue ? svalue[1] : svalue;
}
}
alert(Request.QueryString("id"));
Request = {
QueryString : function(item){
var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
return svalue ? svalue[1] : svalue;
}
}
alert(Request.QueryString("id"));