js实现 路由跳转

来源:互联网 发布:淘宝客好做吗难 编辑:程序博客网 时间:2024/04/27 23:15
<!DOCTYPE html><html lang="en">    <head>        <meta charset="utf-8">        <style>            #display{width: 300px;height: 300px}        </style>    </head>    <body>    <div id="app">        <p><a href="#/">home-first</a></p>        <p><a href="#/home">home</a></p>        <p><a href="#/contact">contact</a></p>        <p><a href="#/news">news</a></p>    </div>    <div id="display">    </div>    <script type="text/javascript">        function Router(){            this.paths={};            this.curPath='';        }        Router.prototype={            path:function(str,callback){                var func=callback||function(){};                this.paths[str]=func;            },            refresh:function(){                this.curPath=location.hash.slice(1)||'/home'                this.paths[this.curPath]()            },            init:function(){                window.addEventListener('load',this.refresh.bind(this),false)                window.addEventListener('hashchange',this.refresh.bind(this),false)            }        }        var display=document.getElementById('display');        var r=new Router();        r.path('/home',function(){            display.innerHTML='home';            display.style.background='yellow'        })        r.path('/contact',function(){            display.innerText='contact';            display.style.background='black'        })        r.path('/news',function(){            display.innerText='news';            display.style.background='green'        })        r.init()    </script>    </body></html>
  • 这里的关键事load和hashchange事件,通过监测路由变化而得到内容的变化
  • this.paths是存储页面内容的对象
  • this.curPath是存储当前路由

bind的实现

    function a(fn,context) {        var args = Array.prototype.slice.call(arguments,2)        return function() {            var innerArgs = Array.prototype.slice.call(arguments);            var finalArgs = args.concat(innerArgs)            fn.apply(context,finalArgs)        }    }    function main() {        console.log(this.b)    }    Function.prototype.bind = function(context) {        var that = this;        var args = Array.prototype.slice.call(arguments,1)        return function() {            var innerArgs = Array.prototype.slice.call(arguments);            var finalArgs = args.concat(innerArgs)            that.apply(context,finalArgs)        }    }
0 0
原创粉丝点击