萬盛學電腦網

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

jQuery 延遲跳轉實作:setTimeout 與 Document Ready 整合

前言

頁面載入後延遲跳轉常用於落地頁、維護通知、倒數計時。jQuery 只需確保 DOM 就緒後啟動計時器。

基本實作

<script>
$(function() {
  // DOM ready 後 5 秒跳轉
  setTimeout(function() {
    window.location.href = 'https://www.example.com';
  }, 5000);
});
</script>

進階:可見倒數計時與取消

<div id="redirect-notice">
  5 秒後自動跳轉...
  
</div>

<script>
$(function() {
  const $countdown = $('#countdown');
  const $notice = $('#redirect-notice');
  let remaining = 5;
  let timerId;

  function tick() {
    $countdown.text(remaining);
    if (remaining <= 0) {
      window.location.href = 'https://www.example.com';
      return;
    }
    remaining--;
    timerId = setTimeout(tick, 1000);
  }

  $('#cancel-redirect').click(function() {
    clearTimeout(timerId);
    $notice.hide();
  });

  tick();
});
</script>

注意事項

  • $(fn) 是 $(document).ready(fn) 簡寫,確保 DOM 就緒。
  • 跳轉前若有未完成 AJAX,請改用 beforeunload 或 Promise 等待。
  • SEO 考量:延遲跳轉可能影響爬蟲抓取,重要內容請直接輸出或用 Server-side redirect (301/302)。

總結

jQuery 延遲跳轉核心即 setTimeout + location.href。加入倒數顯示與取消功能可大幅提升用戶體驗,避免突兀導向。

copyright © 萬盛學電腦網 all rights reserved