如下代碼整理於網絡網絡
一、設置或獲取對象指定的文件名或路徑。
window.location.pathname
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.pathname); 則輸出:/topic/indexdom
二、設置或獲取整個 URL 爲字符串。
window.location.href
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.href); 則輸出:http://localhost:8086/topic/index?topicId=361url
三、設置或獲取與 URL 關聯的端口號碼。
window.location.port
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.port); 則輸出:8086spa
四、設置或獲取 URL 的協議部分。
window.location.protocol
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.protocol); 則輸出:http:code
五、設置或獲取 href 屬性中在井號「#」後面的分段。
window.location.hashhtm
六、設置或獲取 location 或 URL 的 hostname 和 port 號碼。
window.location.host
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.host); 則輸出:http:localhost:8086對象
七、設置或獲取 href 屬性中跟在問號後面的部分。
window.location.search
例:http://localhost:8086/topic/index?topicId=361
alert(window.location.search); 則輸出:?topicId=361
blog
window.location
屬性 描述
href 設置或獲取整個 URL 爲字符串。
host 設置或獲取 location 或 URL 的 hostname 和 port 號碼。
protocol 設置或獲取 URL 的協議部分。
port 設置或獲取與 URL 關聯的端口號碼。
hostname 設置或獲取 location 或 URL 的主機名稱部分。
pathname 設置或獲取對象指定的文件名或路徑。
search 設置或獲取 href 屬性中跟在問號後面的部分。
hash 設置或獲取 href 屬性中在井號「#」後面的分段。
1、方法一 var domain = document.domain; 2、方法二 var domain = window.location.host; 3、注意問題 因爲獲取到的當前域名不包括 http://,因此把獲取到的域名賦給 a 標籤的 href 時,別忘了加上 http://,不然單擊連接時導航會出錯。
var url = window.location.href; var url = self.location.href; var url = document.URL; var url = document.location; ie 地址欄顯示的是什麼,獲取到的 url 就是什麼。
首先獲取 Url,而後把 Url 經過 // 截成兩部分,再從後一部分中截取相對路徑。若是截取到的相對路徑中有參數,則把參數去掉。 function GetUrlRelativePath() { var url = document.location.toString(); var arrUrl = url.split("//"); var start = arrUrl[1].indexOf("/"); var relUrl = arrUrl[1].substring(start);//stop省略,截取從start開始到結尾的全部字符 if(relUrl.indexOf("?") != -1){ relUrl = relUrl.split("?")[0]; } return relUrl; } 調用方法:GetUrlRelativePath(); 舉例:假如當前 Url 是 http// www. liangshunet. com/pub/item.aspx?t=osw7,則截取到的相對路徑爲:/pub/item.aspx。
1、獲取Url參數部分 function GetUrlPara() { var url = document.location.toString(); var arrUrl = url.split("?"); var para = arrUrl[1]; return para; } 調用方法:GetUrlPara() 舉例:假如當前 Url 是 http// www. liangshunet. com/pub/item.aspx?t=osw7,則截取到的參數部分爲:t=osw7。
//paraName 等找參數的名稱 function GetUrlParam(paraName) { var url = document.location.toString(); var arrObj = url.split("?"); if (arrObj.length > 1) { var arrPara = arrObj[1].split("&"); var arr; for (var i = 0; i < arrPara.length; i++) { arr = arrPara[i].split("="); if (arr != null && arr[0] == paraName) { return arr[1]; } } return ""; } else { return ""; } } 調用方法:GetUrlParam("id"); 舉例說明: 假如當網頁的網址有這樣的參數 test.htm?id=896&s=q&p=5,則調用 GetUrlParam("p"),返回 5。