1、采用正则表达式获取地址栏参数:( 强烈推荐,既实用又方便!)
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
var myurl=GetQueryString("url");
if(myurl !=null && myurl.toString().length>1){
alert(GetQueryString("url"));
}
若地址栏URL为:abc.html?id=123&url=http://www.maidq.com
那么,但你用上面的方法去调用:alert(GetQueryString(“url”));则会弹出一个对话框:内容就是 http://www.maidq.com
如果用:alert(GetQueryString(“id”));那么弹出的内容就是 123 啦;
2、传统方法
function UrlSearch()
{
var name,value;
var str=location.href; //取得整个地址栏
var num=str.indexOf("?")
str=str.substr(num+1); //取得所有参数 stringvar.substr(start [, length ]
var arr=str.split("&"); //各个参数放到数组里
for(var i=0;i < arr.length;i++){
num=arr[i].indexOf("=");
if(num>0){
name=arr[i].substring(0,num);
value=arr[i].substr(num+1);
this[name]=value;
}
}
}
var Request=new UrlSearch(); //实例化
alert(Request.id);
比如说把这个代码存为1.html,那么我要访问1.html?id=test,这个时候就取到test的值了
3、一些常用window
1, window.location.href
整个URl字符串(在浏览器中就是完整的地址栏)
本例返回值: http://www.maidq.com/index.html?ver=1.0&id=6#imhere
2,window.location.protocol
URL 的协议部分
本例返回值:http:
3,window.location.host
URL 的主机部分
本例返回值:www.maidq.com
4,window.location.port
URL 的端口部分
如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
本例返回值:""
5,window.location.pathname
URL 的路径部分(就是文件地址)
本例返回值:/fisker/post/0703/window.location.html
6,window.location.search
查询(参数)部分
除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
本例返回值:?ver=1.0&id=6
7,window.location.hash
锚点
本例返回值:#imhere