hash路由实现原理
路由(routing): 根据路径决定前端显示的视图
实现常规页面跳转:
9.hash01.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<a href="9.hash01.html"></a>
<a href="10.hash02.html"></a>
<a href="11.hash03.html"></a>
</nav>
<div>
这是第一个视图
</div>
</body>
</html>
10.hash02.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<a href="9.hash01.html"></a>
<a href="10.hash02.html"></a>
<a href="11.hash03.html"></a>
</nav>
<div>
这是第二个视图
</div>
</body>
</html>
11.hash03.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<a href="9.hash01.html"></a>
<a href="10.hash02.html"></a>
<a href="11.hash03.html"></a>
</nav>
<div>
这是第二个视图
</div>
</body>
</html>
用hash实现页面跳转
注意:超级链接(a标签),又叫命名锚记。命名锚记像一个迅速定位器一样是一种页面内的超级链接,运用相当普遍。在JS中hash就是在html中锚点。
先看看什么是hash!!!
window.onhashchange:监听location中的hash变化了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<a href="#view1">视图1</a>
<a href="#view2">视图2</a>
<a href="#view3">视图3</a>
</nav>
<div>
这是第一个视图
</div>
<script>
// 监听location中的hash变化了
window.onhashchange = ()=>{
console.log(location.hash);
};
</script>
</body>
</html>
现在用hash实现页面跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav>
<a href="#view1">视图1</a>
<a href="#view2">视图2</a>
<a href="#view3">视图3</a>
</nav>
<div id="view">
这是第一个视图
</div>
<script>
{
let view = document.querySelector("#view");
window.onhashchange = setView;
function setView(){
let hash = location.hash;
console.log(hash);
switch (hash) {
case "#view1":
view.innerHTML = "这是第一个视图";
break;
case "#view2":
view.innerHTML = "这是第二个视图";
break;
case "#view3":
view.innerHTML = "这是第三个视图";
break;
default:
break;
}
}
}
</script>
</body>
</html>
好了!这就用hash实现了一个页面内的跳转。
目前较为热门的hashrouter,小迪将在后面的篇章阐述!
(后续待补充)