前幾天在院子裡看了一個大牛用js寫了一個路由的,有一句代碼一直不知道怎麼回事,後來就自己寫了一個,寫的比較的粗糙,我覺得把麵向對象的思想都搞得亂七八糟的,不過功能實現了.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js实现路由</title> </head> <body> < a href=" " >white</ a> < a href="#/green" >green</ a> < a href="#/blue" >blue</ a> < a href="#/yellow" >yellow</ a> </body> </html> <script> <span style="color: #0000ff;">function</span><span style="color: #000000;"> Route(){ } Route.prototype.open</span>=<span style="color: #0000ff;">function</span><span style="color: #000000;">(route,callback){ </span><span style="color: #0000ff;">var</span> arr=<span style="color: #000000;">{}; arr[route]</span>=<span style="color: #000000;">callback; window.addEventListener(</span>'hashchange',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){ </span><span style="color: #0000ff;">var</span> temp=<span style="color: #000000;">window.location.hash; </span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> i <span style="color: #0000ff;">in</span><span style="color: #000000;"> arr){ </span><span style="color: #0000ff;">if</span>(i==temp.slice(1<span style="color: #000000;">,temp.length)){ arr[i](); } } }) } window.Route</span>=<span style="color: #0000ff;">new</span><span style="color: #000000;"> Route(); </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> change(color){ </span><span style="color: #0000ff;">var</span> body=document.getElementsByTagName('body')[0<span style="color: #000000;">]; body.style.backgroundColor</span>=<span style="color: #000000;">color; console.log(color); } Route.open(</span>'/',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){ change(</span>''<span style="color: #000000;">); }); Route.open(</span>'/green',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){ change(</span>'green'<span style="color: #000000;">); }); Route.open(</span>'/blue',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){ change(</span>'blue'<span style="color: #000000;">); }); Route.open(</span>'/yellow',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){ change(</span>'yellow'<span style="color: #000000;">); }); </span></script>