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

使用HTML5 pushState时,点击后退/前进按钮div状态无法恢复的问题

解决HTML5 pushState后退/前进时内容不更新的问题

你的问题核心是没有正确处理popstate事件,也没利用pushState存储的状态数据,导致后退/前进时URL变了但div内容没更新。下面是具体的修复方案:

问题分析

  1. 当前popstate事件里调用show("")完全无效,空参数无法触发有效内容返回
  2. pushState已经把内容存在状态里,但你没在后退/前进时读取这个状态
  3. 页面初始加载时,如果URL已经是/steak或/salad,没有自动加载对应内容

修复后的代码

index.js 修改版

// 负责更新页面内容和历史状态
function updateContent(input, content) {
  const resDiv = document.getElementById("menu-res");
  resDiv.innerHTML = content;
  // 存储包含input和content的状态对象,方便后续恢复
  history.pushState({ input, content }, null, input);
}

// 负责发送请求获取内容
function fetchContent(input) {
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      updateContent(input, this.responseText);
    }
  };
  xmlhttp.open("POST", "res.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  const data = `order=${input}`;
  xmlhttp.send(data);
}

// 初始加载时,根据URL恢复状态
window.addEventListener('DOMContentLoaded', function() {
  // 获取当前URL的路径部分(比如 "/steak" 取 "steak")
  const path = window.location.pathname.slice(1);
  if (path === "steak" || path === "salad") {
    fetchContent(path);
  }

  // 绑定按钮点击事件
  document.getElementById("menu-btn-1").addEventListener('click', () => {
    fetchContent("steak");
  });

  document.getElementById("menu-btn-2").addEventListener('click', () => {
    fetchContent("salad");
  });
});

// 处理后退/前进按钮
window.addEventListener('popstate', function(event) {
  // 从state中取出之前存储的内容
  if (event.state) {
    document.getElementById("menu-res").innerHTML = event.state.content;
  } else {
    // 回到初始状态,清空内容
    document.getElementById("menu-res").innerHTML = "";
  }
});

关键修改点

  • 拆分fetchContent和updateContent函数,职责更清晰
  • pushState存储包含input和content的完整状态对象
  • popstate事件直接读取event.state里的内容更新div,无需重复发请求
  • 初始加载时自动根据URL路径加载对应内容,解决刷新后内容为空的问题
  • 合并冗余的DOMContentLoaded监听,减少不必要的代码

额外优化建议

  • 给fetchContent添加loading状态,避免重复点击请求
  • 增加请求失败的处理逻辑(比如状态码非200时的提示)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:57:11