通过监听 URL 变化实现前端路由,使用 hashchange 事件或 History API 动态更新视图。定义路由映射表,根据路径渲染对应内容,支持 HTML 字符串插入或动态创建 DOM 元素。可扩展参数化路由,如匹配 #/user/123 提取用户 ID。初始化视图并处理默认路径与 404,提升单页应用体验。

在单页应用(SPA)中,通过 JavaScript 动态创建和修改 HTML 路由视图是一种常见做法。它能让页面在不刷新的情况下切换内容,提升用户体验。实现这一功能不需要依赖框架,也可以用原生 JS 完成。下面介绍如何使用纯 JavaScript 实现动态路由和视图管理。
理解前端路由的基本原理
前端路由的核心是监听 URL 的变化,并根据路径加载对应的内容。浏览器提供了 History API 和 hashchange 事件 来实现无刷新跳转。
常用方式有两种:
- Hash 路由:基于 URL 中的 # 后面的部分(如 #/home),通过监听 window.onhashchange 触发视图更新。
- History 路由:使用 history.pushState() 和 popstate 事件,实现更干净的 URL(如 /about),但需要服务器配合避免 404。
使用 Hash 实现动态路由
Hash 模式简单易用,适合初学者。以下是实现步骤:
立即学习“前端免费学习笔记(深入)”;
// 定义路由映射
const routes = {
'#/': '首页
欢迎来到主页
',
'#/about': '关于我们
我们是一家前端技术团队
',
'#/contact': '联系我们
'
};
// 获取容器 const app = document.getElementById('app');
// 路由处理函数 function renderView() { const path = window.location.hash || '#/'; const content = routes[path] || '
404
页面未找到
'; app.innerHTML = content; }// 监听 hash 变化 window.addEventListener('hashchange', renderView);
// 初始化视图 renderView();
这样,当用户点击类似 关于我们 的链接时,页面内容会动态更新。
动态创建和插入视图元素
除了直接插入 HTML 字符串,你也可以动态创建 DOM 元素,更适合复杂交互。
例如,为“联系”页面添加一个动态表单:
function createContactView() {
const container = document.createElement('div');
container.innerHTML = '联系我们
';
const form = document.createElement('form');
const input = document.createElement('input');
input.type = 'text';
input.placeholder = '请输入姓名';
const button = document.createElement('button');
button.textContent = '提交';
button.onclick = (e) => {
e.preventDefault();
alert('感谢您的留言!');
};
form.appendChild(input);
form.appendChild(button);
container.appendChild(form);
return container;
}
// 在路由中调用
if (path === '#/contact') {
app.innerHTML = '';
app.appendChild(createContactView());
}
扩展:支持参数化路由
有时需要处理带参数的路径,比如 #/user/123。可以通过正则匹配提取参数。
function handleDynamicRoute() {
const hash = window.location.hash;
const match = hash.match(/#\/user\/(\d+)/);
if (match) {
const userId = match[1];
app.innerHTML = `用户详情
当前查看用户 ID:${userId}
`;
}
}
在 hashchange 事件中调用该函数,即可实现动态参数解析。
基本上就这些。通过监听 URL 变化、维护路由表、动态生成 DOM,就能用原生 JS 实现完整的路由视图系统。不复杂但容易忽略细节,比如默认路径处理和 404 响应。熟练掌握后,再学习 React Router 或 Vue Router 会更容易理解底层逻辑。











