<body>
  <h3>Histort api</h3>
  <a class="api a">a,html</a>
  <a class="api b">b,html</a>

  <script>
    //注册路由
    document.querySelectorAll('.api').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        let link = item.textContent;
        window.history.pushState({name: 'api'},link,link)
      }, false)
    });

    //监听路由
    window.addEventListener('popstate', (e) => {
      console.log({
        location: location.href,
        state: e.state
      });
    }, false)
  </script>

  <p>------------------</p>

  <h3>Hash</h3>
  <a class="hash a">#a.html</a>
  <a class="hash b">#b.html</a>

  <script>
    //注册路由
    document.querySelectorAll('.hash').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        let link = item.textContent;
        location.hash=link;
      }, false)
    });

    //监听路由
    window.addEventListener('hashchange', (e) => {
      console.log({
        location: location.href,
        hash: location.hash
      });
    }, false)
  </script> 
</body>

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-07-04
  • 2021-09-05
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2021-10-07
  • 2022-12-23
相关资源
相似解决方案