实现一个简易的前端路由
<body>
<a id="black" href="#/black">black</a>
<a id="red" href="#/red">red</a>
<a id="yellow" href="#/yellow">yellow</a>
<script>
function Router() {
this.route = {};
this.currentUlr = '';
this.init();
}
Router.prototype.router = function (path, cb) {
this.route[path] = cb || function () {};
}
Router.prototype.freshRoute = function () {
this.currentUlr = window.location.hash.slice(1);
this.route[this.currentUlr] && this.route[this.currentUlr]();
}
Router.prototype.init = function () {
window.addEventListener('load', this.freshRoute.bind(this), false);
window.addEventListener('hashchange', this.freshRoute.bind(this), false);
}
var router = new Router();
router.router('/black', function () {
document.querySelector('body').style.backgroundColor = 'black';
})
router.router('/red', function () {
document.querySelector('body').style.backgroundColor = 'red';
})
router.router('/yellow', function () {
document.querySelector('body').style.backgroundColor = 'yellow';
})
</script>
</body>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。