第一种hash
/*
*路由对象负责对应的路径执行对应的函数
*/
1. function router() {
this.routes = {};
this.currentRoutes = \'\';
}
/*
* refresh 绑定hashchange 函数时候调用
*/
router.prototype.refresh = function () {
// 把第一个#去掉
var currentUrl = location.hash.slice(1);
// 调用对应的函数来执行;
if(this.routes[currentUrl]) {
this.routes[currentUrl]();
}
}
router.prototype.init = function () {
window.addEventListener(\'load\', this.refresh.bind(this));
window.addEventListener(\'hashchange\', this.router.refresh.bind(this))
}
/*
*path 路径
* cb 回调函数
*/
router.prototype.register = function(path, cb) {
if( !this.routes [path] ) {
this.routes[path] = cb;
}
}
// 改变颜色
function changeColor(color) {
document.body.style[\'background-color\'] = color;
}
// 初始化路由对象
var router = new router();
// 初始化函数,绑定监听事件
router.init();
// 添加对应的路由执行函数
router.register(\'/\', changeColor.bind(null, \'red\'));
router.register(\'/green\', changeColor.bind(null, \'green\'));
router.register(\'/blue\', changeColor.bind(null, \'blue\'));