萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 頁面跳轉方法大全(location、history、open、延遲、彈窗確認)

常用跳轉方式速查

場景代碼示例說明
當前頁直接跳轉window.location.href = 'url';最常用,會在歷史記錄留下記錄
替換當前歷史記錄跳轉window.location.replace('url');不留歷史,用戶無法「返回」上頁
重新加載當前頁window.location.reload();相當於 F5
返回上一頁window.history.back(); / window.history.go(-1);等同於瀏覽器後退按鈕
前進/後退 N 頁window.history.go(n);n 為正前進,負後退
新窗口打開window.open('url', '_blank', 'width=600,height=400');可控制窗口特性,會被攔截器攔截
頂級窗口跳轉(跳出 iframe)top.location.href = 'url';用於 iframe 被嵌入時強制頂層導航
延遲跳轉(倒計時)見下方完整示例常用於提示頁、支付成功頁
彈窗確認後跳轉見下方示例用於注銷、危險操作二次確認

1. 直接跳轉

<script>
window.location.href = 'https://www.example.com';
</script>

2. 替換模式跳轉(無歷史記錄)

<script>
window.location.replace('https://www.example.com');
</script>

3. 返回上一頁 / 歷史導航

<a href="javascript:history.back()">返回上一頁</a>
<a href="javascript:history.go(-1)">返回上一頁</a>
<script>window.history.go(-2);</script> <!-- 後退兩頁 -->

4. 新窗口打開

<a href="javascript:void(0)" onclick="window.open('https://www.example.com', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes')">新窗口打開</a>

5. 延遲跳轉(帶倒計時顯示)

<span id="countdown">5</span> 秒後自動跳轉...
<script>
var sec = 5;
var timer = setInterval(function() {
    sec--;
    document.getElementById('countdown').innerText = sec;
    if (sec <= 0) {
        clearInterval(timer);
        window.location.href = 'https://www.example.com';
    }
}, 1000);
</script>

6. 彈窗確認跳轉

<script>
function confirmRedirect(url, message) {
    if (confirm(message || '確定要離開當前頁面嗎?')) {
        window.location.href = url;
    }
}
// 用法
// <a href="javascript:confirmRedirect('logout.asp', '確定注銷?')">注銷</a>
</script>

7. 彈窗提示後跳轉(無取消選項)

<script>
function alertRedirect(url, message) {
    alert(message || '即將跳轉...');
    window.location.href = url;
}
</script>

8. HTML Meta 標籤跳轉(無 JS 環境備用)

<meta http-equiv="refresh" content="3;url=https://www.example.com">
<!-- 3 秒後跳轉 -->

9. 表單提交跳轉(POST 跳轉)

<form id="autoSubmit" action="https://www.example.com" method="POST">
    <input type="hidden" name="token" value="abc123">
</form>
<script>document.getElementById('autoSubmit').submit();</script>

10. 避坑指南

  • location.href vs location.assign vs location.replace:`href` 和 `assign` 行為一致(留歷史),`replace` 不留歷史。
  • window.open 被攔截:現代瀏覽器默認攔截非用戶直接點擊觸發的 `open`。必須在用戶交互事件(click、tap)中調用,或引導用戶允許彈窗。
  • iframe 中跳轉:`self.location` 只跳轉 iframe 內部;`top.location` 或 `parent.location` 跳轉父/頂級頁面。
  • SPA 路由跳轉:單頁應用請使用框架路由 API(`router.push`、`$router.replace` 等),切勿直接操作 `location` 導致整頁重載。
copyright © 萬盛學電腦網 all rights reserved