Skip to content

基于浏览器的路由示例,使用URL的hash部分来模拟路由变化,并触发相应的事件或函数。

javascript
<!DOCTYPE html>  
<html lang="en">  
<head>  
<meta charset="UTF-8">  
<meta name="viewport" content="width=device-width, initial-scale=1.0">  
<title>Simple Router</title>  
<script>  
// 路由映射表  
const routes = {  
    '/': function() {  
        document.getElementById('content').textContent = 'Home Page';  
    },  
    '/about': function() {  
        document.getElementById('content').textContent = 'About Page';  
    },  
    '/contact': function() {  
        document.getElementById('content').textContent = 'Contact Page';  
    }  
    // 添加更多路由...  
};  
  
// 初始化路由,根据当前URL的hash部分  
function initRoute() {  
    const hash = window.location.hash.substr(1); // 去除'#'字符  
    if (routes[hash]) {  
        routes[hash](); // 调用对应的路由处理函数  
    } else {  
        routes['/'](); // 默认路由  
    }  
}  
  
// 监听hash变化事件  
window.addEventListener('hashchange', function() {  
    initRoute();  
});  
  
// 页面加载时初始化路由  
window.onload = initRoute;  
</script>  
</head>  
<body>  
  
<nav>  
    <a href="#/">Home</a> |  
    <a href="#/about">About</a> |  
    <a href="#/contact">Contact</a>  
</nav>  
  
<div id="content"></div> <!-- 这里显示路由内容 -->  
  
</body>  
</html>

在这个例子中,我们定义了一个routes对象,它包含了不同的路由路径和对应的处理函数。当URL的hash部分发生变化时(例如,用户点击了导航链接),hashchange事件会被触发,然后调用initRoute函数来根据新的hash值更新页面内容。