얼마 전 마당에서 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>