实现一个简易的前端路由

实现一个简易的前端路由

<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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Cisco PT模拟实验(4) 交换机的VLAN划分与配置 实验目的: 掌握虚拟LAN(VLAN)的基本配置; ...
    anything都不会阅读 1,248评论 2 3
  • 第三章 靳向南在还差两年退休的时候,就开始准备退休的事情,那时候他在大街上溜达着,寻摸着退休后能干点什么。他猛然看...
    刘老师_9e2c阅读 529评论 0 0
  • 我今天读的,是数学花园漫游记我,我读了一个故事,讲的是怎么求不规则图形的面积,比如北京在地图上1厘米等于 40千米...
    张富霖ABC阅读 452评论 0 0
  • 我知道他已经老了 我已长大了 于是他开始埋怨我了 他埋怨我不想家 两月一个电话 等风来 蒲公英才能飞 风已经没力气...
    郝圆阅读 154评论 0 1
  • 我总结出我们家族的五大核心品质:孝顺,善良有爱心,能吃苦,勤劳,节约 孝顺是中华美德,因为父母的影响...
    067a11d57f81阅读 179评论 0 0