Home >Web Front-end >HTML Tutorial >A route written in js
A few days ago, I saw an expert writing a routing using js in the yard. There was a line of code that I didn’t know what was going on. Then I wrote one myself. The writing was relatively rough. I think the object-oriented thinking It’s all a mess, but the function is implemented.
<!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>