国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js實現自定義路由

2019-11-19 17:44:31
字體:
來源:轉載
供稿:網友

本文實現自定義路由,主要是事件hashchange的使用,然后根據我們的業務需求封裝。

首先實現一個router的類,并實例化。

function _router(config){ this.config = config ? config : {}; } _router.prototype = { event:function(str,callback){  var events = str.split(' ');  for (var i in events) window.addEventListener(events[i],callback,false); },init: function() { this.event('load hashchange',this.refresh.bind(this)); return this;},refresh: function() { this.currentUrl = location.hash.slice(1) || '/'; this.config[this.currentUrl]();},route: function(path,callback){ this.config[path] = callback || function(){};}}function router (config){ return new _router(config).init();}

上邊唯一需要注意的是,在使用addEventListener的時候,需要注意bind函數的使用,因為我是踩了坑,這才體會到$.proxy()。

上邊使用的時候可以使用兩種方法進行注冊,但第二種是依賴第一種的。

方法一:

var Router = router({ '/' : function(){content.style.backgroundColor = 'white';}, '/1': function(){content.style.backgroundColor = 'blue';}, '/2': function(){content.style.backgroundColor = 'green';}})

方法二:

Router.route('/3',function(){ content.style.backgroundColor = 'yellow'; })

完整代碼:

<html> <head>  <title></title> </head> <body>  <ul>   <li><a href="#/1">/1: blue</a></li>   <li><a href="#/2">/2: green</a></li>   <li><a href="#/3">/3: yellow</a></li>  </ul>  <script>  var content = document.querySelector('body');  function _router(config){   this.config = config ? config : {};   }   _router.prototype = {   event:function(str,callback){    var events = str.split(' ');    for (var i in events) window.addEventListener(events[i],callback,false);   },   init: function() {    this.event('load hashchange',this.refresh.bind(this));    return this;   },   refresh: function() {    this.currentUrl = location.hash.slice(1) || '/';    this.config[this.currentUrl]();   },   route: function(path,callback){    this.config[path] = callback || function(){};   }  }  function router (config){   return new _router(config).init();  }  var Router = router({   '/' : function(){content.style.backgroundColor = 'white';},   '/1': function(){content.style.backgroundColor = 'blue';},   '/2': function(){content.style.backgroundColor = 'green';}  })  Router.route('/3',function(){   content.style.backgroundColor = 'yellow';  })  </script> </body></html><script> </script>

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 怀安县| 辽中县| 南丹县| 噶尔县| 普兰店市| 东宁县| 安平县| 怀远县| 北辰区| 营山县| 铅山县| 贵港市| 花垣县| 澄江县| 集安市| 育儿| 什邡市| 沛县| 大余县| 孟津县| 二手房| 阿拉善左旗| 肥东县| 斗六市| 彰武县| 赫章县| 大姚县| 临夏县| 江都市| 闻喜县| 曲沃县| 尼木县| 临沭县| 临夏市| 自治县| 泰宁县| 金乡县| 信阳市| 大足县| 洮南市| 香河县|