首页 / JAVASCRIPT / js实现自定义路由
js实现自定义路由
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了js实现自定义路由,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2307字,纯文字阅读大概需要4分钟。
内容图文
![js实现自定义路由](/upload/InfoBanner/zyjiaocheng/303/e8cc19cd9ac24bb1a5f040dc000c6172.jpg)
首先实现一个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>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!
更多js实现自定义路由相关文章请关注PHP中文网!
内容总结
以上是互联网集市为您收集整理的js实现自定义路由全部内容,希望文章能够帮你解决js实现自定义路由所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。