您的位置:首页 > Web前端 > JavaScript

JavaScript——js获取url方法,方便以后页面的跳转

2015-11-01 09:39 579 查看
1.获取URL
 获取url方法,直接用location就可以了,window.location或window.loation.href也可以。


<script language="javascript"> 

var t1=location

var t2=window.location

var t3=window.location.href;  

</script> 

2.分析URL
 运用location获取的url属性为object,需要先将其转换为字符


<script> 

var t1=location

var t2=window.location

var t3=window.location.href; 

document.write("location型为: "+typeof(t1)+"<br />"+"window.location型为: "+typeof(t2)+"<br />"+"window.location.href型为: "+typeof(t3)); 

</script> 

location进行处理,首先将其转换为字符串" title="字符串">字符串,用函数toString(),URL.toString();

<script> 

var t1=location

var URL=t1.toString(); 

document.write("location型为: "+typeof(t1)+"<br />"+"URL型为: "+typeof(URL)); 

</script> 

完整的URL由这几个部分构成:
 scheme://host:port/path?query#fragment


scheme = 通信协议 (常用的http,ftp,maito等)
 host = 主机 (域名或IP)
 port = 端口号 
 path = 路径


query = 查询 

 http://hexun.com.com:80/seo/?ver=1.0&id=6#imhere

我们可以用javascript获得其中的各个部分
 1, window.location.href
 整个URl字符串" title="字符串">字符串(在浏览器中就是完整地址栏" title="地址栏">地址栏)


2,window.location.protocol
 URL 的协议部分
   返回值:http:


3,window.location.host
 URL 的主机部分
 本例返回值" title="返回值">返回值:hexun.com


4,window.location.port
 URL 的端口部分
 如果采用默认的80端口(update:即使添加了:80),那么返回值" title="返回值">返回值并不是默认的80而是空字符
 本例返回值" title="返回值">返回值:”"


5,window.location.pathname
 URL 的路径部分(就是文件地址)
 本例返回值" title="返回值">返回值:/seo/


6,window.location.search
 查询(参数)部分
 除了给动态言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
 本例返回值" title="返回值">返回值:?ver=1.0&id=6


7,window.location.hash
 锚点
 本例返回值" title="返回值">返回值:#imhere


————————————————————————————————

浏览器兼容:

<script language = javascript> 
function request(paras){ 
var url = location.href;  
var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");  
var paraObj = {}  
for (i=0; j=paraString[i]; i++){  
paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);  
}  
var returnValue = paraObj[paras.toLowerCase()];  
if(typeof(returnValue)=="undefined"){  
return "";  
}else{  
return returnValue;  
}  

var theurl=request('url'); 
var theimg=request('img'); 
document.writeln("<a href='"  + theurl + "' target=_blank><img src=" + theimg + " width=750 height=450 border=0></a>"); 
</script>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  url javascript