1. 程式人生 > >jquery獲取當前頁面url及url引數的方法

jquery獲取當前頁面url及url引數的方法

jquery獲取url的函式的資料

1、設定或獲取物件指定的檔名或路徑。
window.location.pathname
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.pathname); 則輸出:/topic/index

2、設定或獲取整個 URL 為字串。
window.location.href
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.href); 則輸出:http://localhost:8086/topic/index?topicId=361

3、設定或獲取與 URL 關聯的埠號碼。
window.location.port
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.port); 則輸出:8086

4、設定或獲取 URL 的協議部分。
window.location.protocol
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.protocol); 則輸出:http:

5、設定或獲取 href 屬性中在井號“#”後面的分段。
window.location.hash
設定或獲取 location 或 URL 的 hostname 和 port 號碼。
window.location.host
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.host); 則輸出:http:localhost:8086

6、設定或獲取 href 屬性中跟在問號後面的部分。
window.location.search
例:
 

http://localhost:8086/topic/index?topicId=361
alert(window.location.search); 則輸出:?topicId=361

7、window.location
屬性  描述
hash   設定或獲取 href 屬性中在井號“#”後面的分段。
host設定或獲取 location 或 URL 的 hostname 和 port 號碼。
hostname  設定或獲取 location 或 URL 的主機名稱部分。
href 設定或獲取整個 URL 為字串。
pathname  設定或獲取物件指定的檔名或路徑。
port 設定或獲取與 URL 關聯的埠號碼。
protocol  設定或獲取 URL 的協議部分。
search設定或獲取 href 屬性中跟在問號後面的部分。

jquery獲取url引數的例子

1、html:
 

複製程式碼 程式碼示例: <!DOCTYPE html>  
<html>   
<head>   
<title>jquery獲取url引數-www.jbxue.com</title>   
<style type='text/css'>  
</style>  
</head>   
<body>  
</body>   
<script type='text/javascript' src='./jquery-1.8.2.js'></script>  
<script type='text/javascript' src='jqueryPlugin.js'></script>  
<script type='text/javascript'>   
$(document).ready(function(){  
// 訪問該頁面時,在url末尾新增?picid=8  
console.log(window.location.href);  
console.log($.getUrlParam('picid'));  
console.log(getUrlParam('picid'));  
});  
  
function getUrlParam(name){  
//構造一個含有目標引數的正則表示式物件  
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");  
//匹配目標引數  
var r = window.location.search.substr(1).match(reg);  
//返回引數值  
if (r!=null) return unescape(r[2]);  
return null;  
}  
</script>   
</html> 

2、jqueryPlugin.js:
 

複製程式碼 程式碼示例: (function($){  
$.getUrlParam = function(name)  
{  
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");  
var r = window.location.search.substr(1).match(reg);  
if (r!=null) return unescape(r[2]); return null;  
}  
})(jQuery); 

結果:
 

file:///C:/Users/zhanglei/Desktop/1.html?picid=8
8
8