window.location 對象用於獲得當前頁面的地址 (URL),並把瀏覽器重定向到新的頁面。
Window Locationwindow.location 對象在編寫時可不使用 window 這個前綴。一些例子:
一些實例:
location.hostname 返回 web 主機的域名
location.pathname 返回當前頁面的路徑和文件名
location.port 返回 web 主機的埠 (80 或 443)
location.protocol 返回所使用的 web 協議(http: 或 https:)
Window Location Hreflocation.href 屬性返回當前頁面的 URL。
返回(當前頁面的)整個 URL:
<script>
document.write(location.href);
</script>
以上代碼輸出為:
https://www.runoon.com/javascript/js-tutorial/javascript-window-location.html
Window Location Pathnamelocation.pathname 屬性返回 URL 的路徑名。
返回當前 URL 的路徑名:
<script>
document.write(location.pathname);
</script>
以上代碼輸出為:
/javascript/js-tutorial/javascript-window-location.html
Window Location Assignlocation.assign() 方法加載新的文檔。
加載一個新的文檔:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>奔月教程(runoon.com)</title>
<script>
function newDoc() {
window.location.assign("https://www.runoon.com")
}
</script>
</head>
<body>
<input type="button" value="加載新文檔" onclick="newDoc()">
</body>
</html>
點擊下方「閱讀原文」可親試效果
長按二維碼關注公眾號,查閱更多教程