space-think

第一种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\'));

 

分类:

技术点:

相关文章:

  • 2021-12-12
  • 2022-01-01
  • 2021-10-14
  • 2019-10-11
  • 2021-09-29
  • 2021-12-13
猜你喜欢
  • 2022-01-01
  • 2021-06-09
  • 2018-12-17
  • 2018-12-13
  • 2021-08-16
  • 2022-01-01
  • 2019-07-26
相关资源
相似解决方案