Heim > Artikel > Web-Frontend > Eine in js geschriebene Route
Vor ein paar Tagen sah ich einen großartigen Kerl, der ein Routing mit JS schrieb. Ich wusste nicht, was los war. Das Schreiben war relativ grob . Ich denke, die objektorientierten Gedanken waren völlig durcheinander, aber die Funktion wurde realisiert
<!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>