1 <a class="api a">a.html</a> 2 <a class="api b">b.html</a> 3 <script> 4 // 注册路由 5 document.querySelectorAll(‘.api‘).forEach(item=>{ 6 item.addEventListener(‘click‘,(e)=>{ 7 e.preventDefault(); 8 let link=item.textContent 9 window.history.pushState({name:‘api‘},link,link); 10 },false) 11 }); 12 // 监听路由 13 window.addEventListener(‘popstate‘,(e)=>{ 14 console.log({ 15 location:location.href, 16 state:e.state 17 }); 18 },false) 19 </script> 20 <hr> 21 <h3>Hash</h3> 22 <a class="hash c">c.html</a> 23 <a class="hash d">d.html</a> 24 <script> 25 document.querySelectorAll(‘.hash‘).forEach(item=>{ 26 item.addEventListener(‘click‘,(e)=>{ 27 e.preventDefault(); 28 let link=item.textContent; 29 location.hash=link; 30 },false) 31 }); 32 window.addEventListener(‘hashchange‘,(e)=>{ 33 console.log({ 34 location:location.href, 35 hash:location.hash 36 }) 37 }) 38 </script>