You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现跳转至/something/之前页面的goBack按钮?

实现直接返回至/something/系列页面之前的页面

要解决这个问题,核心是跳过/something/及其所有分页页面的历史记录,直接回到进入该系列前的页面,而不是默认的逐步回退。下面是两种可行的实现方案,适配你的多页应用场景(分页为独立页面断点):

方案一:记录进入时的历史长度,计算回退步数

这种方法通过sessionStorage记录用户第一次进入/something/系列页面时的历史栈长度,点击返回按钮时计算需要回退的总步数,直接跳转至目标页面。

代码实现

// 在所有/something/系列页面(首页+分页)中添加以下脚本
document.addEventListener('DOMContentLoaded', function() {
  const currentPath = window.location.pathname;
  const isInSomethingSeries = currentPath.startsWith('/something/');

  if (isInSomethingSeries) {
    // 如果是/something/首页,刷新时重新记录历史长度
    if (currentPath === '/something/' || currentPath === '/something') {
      sessionStorage.setItem('somethingEntryHistoryLength', window.history.length.toString());
    } 
    // 如果是分页页面且未记录过进入长度,补充记录
    else if (!sessionStorage.getItem('somethingEntryHistoryLength')) {
      sessionStorage.setItem('somethingEntryHistoryLength', window.history.length.toString());
    }
  } else {
    // 离开/something/系列页面时,清除记录避免干扰
    sessionStorage.removeItem('somethingEntryHistoryLength');
  }
});

// 绑定返回按钮的点击事件
document.getElementById('goBackBtn').addEventListener('click', function() {
  const entryHistoryLength = parseInt(sessionStorage.getItem('somethingEntryHistoryLength'));
  
  if (entryHistoryLength) {
    // 计算需要回退的步数:当前历史长度 - 进入时的长度 + 1
    // +1 是为了跳过进入/something/的那一条历史记录
    const steps = window.history.length - entryHistoryLength + 1;
    window.history.go(-steps);
    
    // 回退后清除记录,防止后续误触发
    sessionStorage.removeItem('somethingEntryHistoryLength');
  } else {
    // 无记录时,默认回退一步
    window.history.back();
  }
});

工作原理

举个实际场景例子:

  1. 用户从页面/home/(历史栈长度为3)进入/something/,此时历史栈长度变为4,我们将4存入sessionStorage。
  2. 用户依次跳转至/something/2/(长度5)、/something/4/(长度6)。
  3. 点击返回按钮时,计算步数:6 - 4 + 1 = 3,调用history.go(-3)直接回到/home/。

注意事项

  • sessionStorage是标签页级别的存储,关闭标签页会自动清除,不会影响其他标签页的操作。
  • 如果用户直接从外部进入分页页面(比如直接打开/something/2/),代码会自动记录此时的历史长度,确保返回正确。
  • 当用户离开/something/系列页面后,记录会被自动清除,避免后续其他页面的返回操作受影响。

方案二:逐步回退直到离开系列页面(备选)

如果担心历史长度计算的准确性(比如页面刷新导致长度异常),可以采用逐步回退并校验页面路径的方式,直到离开/something/系列:

document.getElementById('goBackBtn').addEventListener('click', function() {
  function navigateBack() {
    window.history.back();
    
    // 监听回退后的页面变化,判断是否已离开系列
    window.addEventListener('popstate', function checkPage() {
      if (!window.location.pathname.startsWith('/something/')) {
        window.removeEventListener('popstate', checkPage);
        sessionStorage.removeItem('inSomethingSeries');
      } else {
        // 仍在系列内,继续回退
        navigateBack();
      }
    }, { once: true });
  }

  // 标记当前处于系列页面中
  sessionStorage.setItem('inSomethingSeries', 'true');
  navigateBack();
});

优缺点

  • 优点:无需依赖历史长度,路径校验更直接。
  • 缺点:回退过程中会逐个加载中间的分页页面,体验不如方案一流畅。

内容的提问来源于stack exchange,提问作者PChristina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:49:36