本文彙總 JavaScript 頁面跳轉的常見實作方式,供日常開發參考。
做 Web 開發的人都知道,頁面之間的跳轉有非常多種寫法。但真正有效的跳轉往往事半功倍——選對方式,後續的歷史紀錄、框架環境與使用者體驗才會如預期。以下整理日常開發中常用到的幾種。
<script language="javascript" type="text/javascript"> window.location.href = "login.jsp?backurl=" + window.location.href; </script>
不帶參數的版本:
<script>window.location.href='https://www.baidu.com';</script>
<script language="javascript">
alert("返回");
window.history.back(-1);
</script>
也可以直接寫在標籤屬性裡:
<a href="javascript:history.go(-1)">返回上一步</a>
<a href="<%=Request.ServerVariables("HTTP_REFERER")%>">返回上一步</a>
<script language="javascript">
window.navigate("top.jsp");
</script>
<script language="JavaScript"> self.location = 'top.htm'; </script>
<script language="javascript">
alert("非法訪問!");
top.location = 'xx.aspx';
</script>
<input name="pclog" type="button" value="GO" onClick="location.href='login.aspx'">
<a href="javascript:" onClick="window.open('login.aspx','','height=500,width=611,scrollbars=yes,status=yes')">開新窗口</a>
把三種主要行為做成按鈕對照,差異一目了然:
<head>
<script language="javascript">
function old_page() {
window.location = "login.aspx"
}
function replace() {
window.location.replace("login.aspx")
}
function new_page() {
window.open("login.aspx")
}
</script>
</head>
<body>
<input type="button" onclick="new_page()" value="在新窗口打開"/>
<input type="button" onclick="old_page()" value="跳轉後有後退功能"/>
<input type="button" onclick="replace()" value="跳轉後沒有後退功能"/>
</body>
三個按鈕分別示範:window.open() 開新視窗、保留原頁;window.location 現頁跳轉並留下歷史紀錄,可後退;window.location.replace() 現頁跳轉但把目前頁從歷史中移除,後退時會跳過它。
實務上判斷很簡單:
replace(),避免使用者按返回時重複送出資料。location.href。top.location 而非 self.location。window.open() 並加上 noopener,以免新頁透過 window.opener 反向操作你的頁面。另外提醒,window.navigate() 屬 IE 專屬 API,其他瀏覽器不支援,新專案不建議使用。
希望本文所述對你的 JavaScript 開發有所幫助。