index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>router</title> </head> <body> <ul> <li to="/movie">电影</li> <li to="/theater">影院</li> </ul> <div id="view"></div> <div> <button id="back">back</button> <button id="go">go</button> </div> <script src="./history.js"></script> </body> </html>hash.js
const view = document.querySelector('#view') const Movie = () => { view.innerHTML = ` <div>电影列表</div> ` } const Theater = () => { view.innerHTML = ` <div>影院列表</div> ` } window.addEventListener('load', Movie, false) window.addEventListener('hashchange', () => { let hash = location.hash switch(hash) { case '#/movie': Movie() break; case '#/theater': Theater() break; default: Movie() } }, false)history.js
const history = window.history const lis = document.querySelectorAll('li') const Movie = () => { view.innerHTML = ` <div>电影列表</div> ` } const Theater = () => { view.innerHTML = ` <div>影院列表</div> ` } function render() { let pathname = location.pathname switch(pathname) { case '/': case '/movie': // history.pushState({id: 2}, '', '/movie') Movie() break; case '/theater': // history.pushState({id: 2}, '', '/theater') Theater() break; default: break; } } // popstate, 在浏览器的前进后退按钮被点击的时候触发 window.addEventListener('popstate', () => { render() }, false) document.querySelector('#back').addEventListener('click', () => { history.back() }, false) document.querySelector('#go').addEventListener('click', () => { history.go(1) console.log(history.state) }, false) lis.forEach((li, index) => { li.addEventListener('click', () => { const to = li.getAttribute('to') history.pushState({id: 2}, '', to) render() }, false) })