1. 程式人生 > 其它 >有必要掌握的window.location的細節

有必要掌握的window.location的細節

JS, window, location

window.location會返回一個Location的例項物件(只讀,其會連結到當前物件的位置URL上),其包含著有關當前文件的位置資訊。

location物件除了會掛載到window物件上,還可以通過document物件(window.document)訪問:

window.location === window.document.location; // true
window.document.location instanceof Location; // true

雖然Location物件是隻讀的,但我們仍可以對它賦值(DOMString):

window.location = 'http(s)://xxx';

//等價於 window.location.href = 'http(s)://xxx';

location物件的屬性:

1. href

// 返回包含整個URL的DOMString
window.location.href;
/**
 *
 * window.location.href 的返回結果的資訊中包括以下幾部分:
 * 1. window.location.protocol
 * 2. window.location.hostname
 * 3. window.location.port
 * 4. window.location.pathname 
 * 5. window.location.hash
 * 6. window.location.search
 * 注:不等於各部分的直接拼接
 
*/

2. host

// 域名(+port ?)
window.location.host;

// 包含:
window.location.hostname 和 window.location.port

3. protocal

// HTTP 協議
window.location.protocol;

3. hostname

// URL域名的DOMString
window.location.hostname;

4. port

// 埠號
window.location.port;

5. pathname

// URL的路徑部分
window.location.pathname;

6. search

// URL引數
window.location.search;

7. hash

// 塊識別符號
window.location.hash;

8. origin

// 頁面來源(協議+主機地址,即protocol + host)
window.location.origin;