JS路由
来源:互联网 发布:搞笑文案知乎 编辑:程序博客网 时间:2024/06/05 08:28
一个极简前端路由实现
说一下前端路由实现的简要原理,以 hash 形式(也可以使用 History API 来处理)为例,当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。直接看代码或许更直观。
function Router() { this.routes = {}; this.currentUrl = '';}Router.prototype.route = function(path, callback) { this.routes[path] = callback || function(){};};Router.prototype.refresh = function() { this.currentUrl = location.hash.slice(1) || '/'; this.routes[this.currentUrl]();};Router.prototype.init = function() { window.addEventListener('load', this.refresh.bind(this), false); window.addEventListener('hashchange', this.refresh.bind(this), false);}window.Router = new Router();window.Router.init();
上面路由系统 Router 对象实现,主要提供三个方法
- init 监听浏览器 url hash 更新事件
- route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
- refresh 执行当前url对应的回调函数,更新页面
Router 调用方式以及呈现效果如下:点击触发 url 的 hash 改变,并对应地更新内容(这里为 body 背景色)
<ul> <li><a href="#/">turn white</a></li> <li><a href="#/blue">turn blue</a></li> <li><a href="#/green">turn green</a></li> </ul>
var content = document.querySelector('body');// change Page anythingfunction changeBgColor(color) { content.style.backgroundColor = color;}Router.route('/', function() { changeBgColor('white');});Router.route('/blue', function() { changeBgColor('blue');});Router.route('/green', function() { changeBgColor('green');});
0 0
- JS路由
- Node.js express路由
- Node.Js路由
- 代码段-JS路由
- Node.js 路由
- Node.js 路由
- Node.js 路由
- Node.Js - 路由Router
- angular js路由
- Express.js路由详解
- js URL 地址路由
- Node.js 路由
- 08node.js路由
- angular.js 嵌套路由
- Node.js 路由
- nodejs动态路由js
- js实现 路由跳转
- node.js 路由控制
- centos7下 tomcat8启动慢问题
- 关于UGUI的实例化
- Toorbar的基础使用
- apt update error "E: The package lists or status file could not be parsed or opened."
- 理解AES对称加密
- JS路由
- struts2工作原理
- 函数的调用过程,栈帧的创建和销毁。
- java错误-java.lang.ClassNotFoundException: org.aspectj.lang.annotation.Around
- maven的打包插件
- Android 开机进入Launcher瞬间的切屏问题!
- 一些常用的前端基础操作
- Intel® Parallel Studio XE Cluster Edition for Linux* 2017 安装
- Mysql多种查询速度比较