当前位置:Gxlcms > JavaScript > JS实现简单路由器功能的方法

JS实现简单路由器功能的方法

时间:2021-07-01 10:21:17 帮助过:7人阅读

本文实例讲述了JS实现简单路由器功能的方法。分享给大家供大家参考。具体实现方法如下:

  1. var wawa = {};
  2. wawa.Router = function(){
  3. function Router(){
  4. }
  5. Router.prototype.setup = function(routemap, defaultFunc){
  6. var that = this, rule, func;
  7. this.routemap = [];
  8. this.defaultFunc = defaultFunc;
  9. for (var rule in routemap) {
  10. if (!routemap.hasOwnProperty(rule)) continue;
  11. that.routemap.push({
  12. rule: new RegExp(rule, 'i'),
  13. func: routemap[rule]
  14. });
  15. }
  16. };
  17. Router.prototype.start = function(){
  18. console.log(window.location.hash);
  19. var hash = location.hash, route, matchResult;
  20. for (var routeIndex in this.routemap){
  21. route = this.routemap[routeIndex];
  22. matchResult = hash.match(route.rule);
  23. if (matchResult){
  24. route.func.apply(window, matchResult.slice(1));
  25. return;
  26. }
  27. }
  28. this.defaultFunc();
  29. };
  30. return Router;
  31. }();
  32. var router = new wawa.Router();
  33. router.setup({
  34. '#/list/(.*)/(.*)': function(cate, id){
  35. console.log('list', cate, id);
  36. },
  37. '#/show/(.*)': function(id){
  38. console.log('show', id);
  39. }
  40. }, function(){
  41. console.log('default router');
  42. });
  43. router.start();

希望本文所述对大家的javascript程序设计有所帮助。

更多JS实现简单路由器功能的方法相关文章请关注PHP中文网!

人气教程排行