实现一个简易的前端路由
<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>
网友评论