← 中文资源

简体中文版本

hashchange 把状态同步到 URL fragment

监听 hashchange 把 location.hash 映射成视图状态:每次切换都是可分享的 URL,前进后退能回放视图,未知 fragment 回落到默认页。

阅读英文原文

实现说明

hashchange 把状态同步到 URL fragment以函数 renderView为骨架。

使用要点

  • 用到了 window,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 演示输出是带标签的(render:、views:),每个操作都会留下自己的一行标注。

常见问题

「hashchange 把状态同步到 URL fragment」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(window),Node 里不存在。请在页面或 DevTools 控制台中运行。

主签名形如 function renderView()

核心语句

const TABS = new Set(['overview', 'logs', 'settings']);
window.addEventListener('hashchange', renderView);

代码示例

const TABS = new Set(['overview', 'logs', 'settings']);

function renderView() {
  // '#/logs' style fragments keep the scheme forward-compatible
  const raw = location.hash.slice(1).replace(/^\//, '');
  const view = TABS.has(raw) ? raw : 'overview';
  console.log('render:', view);
  return view;
}

// hashchange fires after the fragment changes — back/forward included.
window.addEventListener('hashchange', renderView);

// Navigating to an unknown fragment falls back to the default view.
location.hash = '#/logs';
const first = renderView();

location.hash = '#/does-not-exist';
const second = renderView();

// Direct assignment rewinds the entry so the browser history stays coherent.
location.hash = '#/overview';
const third = renderView();

console.log('views:', first, second, third);