在做前端開發時,頁面跳轉是經常會用到的操作。以下整理幾種常見的 JavaScript 跳轉寫法,並進一步說明 window.location 相關方法的差異。
第一種:透過 window.location.href 跳轉,並可帶上來源網址
<script language="JavaScript" type="text/javascript">
window.location.href="login.jsp?backurl="+window.location.href;
</script>
第二種:先提示,再返回上一頁
<script language="javascript">
alert("返回");
window.history.back(-1);
</script>
第三種:使用 window.navigate(主要用於舊版 IE)
<script language="javascript">
window.navigate("top.jsp");
</script>
第四種:透過 self.location 跳轉
<script language="JavaScript">
self.location='top.htm';
</script>
第五種:透過 top.location 從框架頂層跳轉
<script language="javascript">
alert("非法訪問!");
top.location='xx.jsp';
</script>
在 JavaScript 中彈出選擇框後再跳轉:
<script language="javascript">
<!--
function logout(){
if (confirm("你確定要註銷身份嗎?是-選擇確定,否-選擇取消")){
window.location.href="logout.asp?act=logout"
}
}
//-->
</script>
在 JavaScript 中彈出提示框後再跳轉:
<script language="javascript">
<!--
function logout(){
alert("你確定要註銷身份嗎?");
window.location.href="logout.asp?act=logout"
}
//-->
</script>
兩者都能把頁面導向另一個網址,那麼差別究竟在哪裡?關鍵體現在「返回」行為上。
舉個例子:我們有三個頁面(a.html、b.html、c.html),預設打開 a.html,再從 a 頁面的連結進入 b.html。現在分別用 window.location.replace("c.html") 與 window.location.href("c.html") 進入 c.html。
從使用者介面看,兩者並無差異。但當 c.html 上有一個「返回」按鈕時,差別就顯現出來了:
用 window.location.href("c.html") 進入時,c 頁面呼叫 window.history.go(-1) 或 window.history.back() 會返回 b.html;而用 window.location.replace("c.html") 進入時,同樣的方法卻會跳回 a.html。
原因在于:window.location.replace 不會向伺服器發送請求進行跳轉,而 history.go(-1)、history.back() 是依據伺服器記錄的請求來決定跳去哪裡,因此會跳到系統預設頁 a.html。相對地,window.location.href 是向伺服器發送請求的跳轉,所以能正確返回 b.html。
簡單來說,replace 相當於「用新頁面替換掉目前的歷史記錄」,不留痕跡;而 href 則會正常留下歷史記錄,可以透過後退按鈕返回。