在JavaScript中,location.href 是最常用的頁面跳轉手段之一,但它的用法遠比表面看起來豐富,尤其是在多框架(frame)環境下,不同前綴會帶來截然不同的跳轉範圍。
以下幾種寫法效果相同,都是在「當前頁面」開啟目標網址:
self.location.href="/url" 當前頁面開啟 URL
location.href="/url" 當前頁面開啟 URL
windows.location.href="/url" 當前頁面開啟 URL
this.location.href="/url" 當前頁面開啟 URL
而下面兩種則會改變跳轉的作用範圍:
parent.location.href="/url" 在父頁面開啟新頁面
top.location.href="/url" 在最頂層頁面開啟新頁面
如果頁面中自訂了命名的 frame,只要把 parent、self、top 換成該 frame 的名稱,就能讓指定框架載入新的網址。
window.location.href = window.location.href; 與 window.location.Reload() 都能重新整理當前頁面,兩者的關鍵區別在於「是否會重新提交表單資料」。當頁面含有已提交的資料時,Reload() 會跳出提示詢問是否重新提交,而重新賦值 href 則相當於再次向該網址送出請求。
在撰寫 ASP.NET 時,我們常用 Response.Redirect 做頁面跳轉。但若希望在跳轉前先彈出提示,Response.Redirect 往往會「搶跑」,導致提示還沒顯示就已經跳走:
復制代碼 代碼如下:
Response.Write("< script>alert('恭喜您,注冊成功!');< /script>");
Response.Redirect("main.html");
此時改用 window.location.href 就能達到「先提示、再跳轉」的效果:
復制代碼 代碼如下:
Response.Write("< script language=javascript>alert('恭喜您,注冊成功!')< /script>");
Response.Write("< script language=javascript>window.location.href='main.html'< /script>");
更進一步,window.location.href 還能實現 Response.Redirect 做不到的事:讓一個框架在執行伺服器端程式碼後,去刷新「另一個」框架的頁面。假設 index.htm 有 frameLeft 與 frameRight 兩個框架,在 frameRight 執行伺服器端程式後刷新 frameLeft,只要在註冊成功後加上:
復制代碼 代碼如下:
Response.Write("< script language=javascript>alert('恭喜您,注冊成功!')< /script>");
Response.Write("< script language=javascript>window.parent.frameLeft.location.href='main.html'< /script>");
如此一來,註冊成功後登入框便能自動刷新成已登入狀態。ASP、PHP 中也普遍採用類似做法。
假設 A、B、C、D 都是 jsp,D 是 C 的 iframe,C 是 B 的 iframe,B 又是 A 的 iframe,那麼在 D 頁面中:
"window.location.href"、"location.href":D 頁面跳轉
"parent.location.href":C 頁面跳轉
"top.location.href":A 頁面跳轉
若 D 頁面中有表單,提交後的跳轉範圍由 target 決定:
<form>:D 頁面跳轉
<form target="_blank">:彈出新頁面
<form target="_parent">:C 頁面跳轉
<form target="_top">:A 頁面跳轉
至於頁面刷新,在 D 頁面中:
"parent.location.reload();":C 頁面刷新(也可透過子視窗的 opener 取得父視窗物件:window.opener.document.location.reload();)
"top.location.reload();":A 頁面刷新
掌握這些層級關係,就能在多框架應用中精準控制「到底是哪一層在跳轉或刷新」。