hashchange 和 pushstate 两种方式做路由的简单实现
第一种
<!DOCTYPE HTML> <title>Line Game - 1</title> <p>you are at <span id="span1">1</span> line</p> <a href="?x=2" onclick="go(1);return false">advance to 2</a>or <a href="?x=0" onclick="go(-1);return false">back to 0</a> <script> var currentPage = 1; function go(num){ currentPage = currentPage+num; setState(currentPage); history.pushState(currentPage,'hahah','?='+currentPage); }; onpopstate = function (event) { setState(event.state); }; var domSpan = document.querySelector('#span1'); function setState(currentPage){ domSpan.textContent = currentPage; document.title = 'line game'+currentPage; document.links[0].href = '?x='+(currentPage+1); document.links[0].textContent= 'advance to'+(currentPage+1); document.links[1].href = '?x='+(currentPage-1); document.links[1].textContent= 'advance to'+(currentPage-1); } </script>
第二种
<a href="#/">首页</a> <a href="#/wether">天气页</a> <a href="#/news">新闻也</a> <div id="div1"></div> <script> function Router(){ this.curUrl = ''; this.routes = {}; this.refresh = function () { this.curUrl = location.hash.slice(1) || '/'; this.routes[this.curUrl](); }; this.init = function () { window.addEventListener('hashchange',this.refresh.bind(this)); window.addEventListener('load',this.refresh.bind(this)); }; this.route = function (path, callback) { this.routes[path] = callback || function(){} } }; var domDiv = document.querySelector('#div1'); var r = new Router(); r.init(); r.route('/', function () { domDiv.textContent = '首页' }); r.route('/news', function () { domDiv.textContent = '新闻' }); r.route('/wether', function () { domDiv.textContent = '天气' }); </script>