前端路由的实现本质:检测URL变化,获取url地址,解析url匹配页面;
检测URL变化有两种方式: hash,HTML5 Historyhtml
Function Router(){ this.currentUrl = ''; this.routes = {}; } Router.prototype.route = function(url, callback){ this.routes[url] = callback || function(){} } Router.prototype.refresh = function(){ this.currentUrl = location.hash.slice(1) || '/'; this.routes[this.currentUrl](); } Router.prototype.init = function(){ window.addEventListener('load', this.refresh.bind(this), false); window.addEventListener('hashchange', this.refresh.bind(this), false); } //使用 var $target = $('#target'); var route = new Router(); route.init(); route.route('/', $target.html('this is index page!!') ); route.route('/page1', $target.html('this is page1!!'));