在以前的web程序中,路由字眼只出现在后台中。但是随着SPA单页面程序的发展,便出现了前端路由一说。单页面顾名思义就是一个网站只有一个html页面,但是点击不同的导航显示不同的内容,对应的url也会发生变化,这就是前端路由做的事。也就是通过JS实时检测url的变化,从而改变显示的内容。
目前很多前端框架都有接口去实现路由,比如vuejs的vue-route等。我们可以利用原生的hashchange事件来模拟一个简单的路由。
实例的html代码:
Document
实例的javascript代码:
function Router(){
    this.routes={};
    this.currentURL=‘‘;
}
Router.prototype.route = function(path,callback){
    this.routes[path] = callback || function(){};
}
Router.prototype.refresh = function(){
    this.currentURL = location.hash.slice(1) || ‘/index‘;
    this.routes[this.currentURL]();
}
Router.prototype.init = function () {
    window.addEventListener(‘load‘,this.refresh.bind(this),false);
    window.addEventListener(‘hashchange‘,this.refresh.bind(this),false);
}
function display_page(id){
    $(".content").eq(id).show().siblings().hide();
}
window.Router = new Router();
Router.route(‘/index‘,function(){
    display_page(0);
})
Router.route(‘/news‘,function(){
    display_page(1);
})
Router.route(‘/about‘,function(){
    display_page(2);
})
window.Router.init();
原文:http://www.cnblogs.com/wozien/p/6597306.html