首页 > 解决方案 > 页面加载和 window.location.assign() 有什么区别

问题描述

当我运行这个 html 代码(名称:Test.html)时:

    <body>
      <a id="button" href="Test.html#no">Reload</a><br>
      <!-- some code here -->
      <a name='no'></a>Messi
      <script>
        let a = 0;
        let reloadbtn = document.querySelector('#button');
        reloadbtn.addEventListener('click', (event)=>{
          console.log(window.location.href);
        })
      </script>
    </body>

通过页面加载/重新加载,然后单击重新加载链接,我在控制台上打印了“path/to/Test.html#no”。 但是,如果我用 刷新页面window.location.assign('Test.html'),然后单击页面上的重新加载链接,我会在控制台上打印“path/to/Test.html” 。

似乎浏览器加载/重新加载使链接window.location.href在单击时正确分配了属性,但没有window.location.assign()

我想知道浏览器加载和 window.location.assign() 之间的区别?JavaScript 如何分别处理这些?可以用 JavaScript 准确地模拟浏览器加载/重新加载吗?

编辑: 当我将脚本代码更改为此:

 <body>
      <a id="button" href="Test.html#no">Reload</a><br>
      <!-- some code here -->
      <a name='no'></a>Messi
      <script>
        let a = 0;
        let reloadbtn = document.querySelector('#button');
        reloadbtn.addEventListener('click', (event)=>{
          console.log(window.location.href);
        setTimeout(()=>(console.log(window.location.href)), 1000);
      })
      </script>
   </body>

并用 刷新页面window.location.assign('Test.html'),然后单击重新加载链接,我在控制台上打印了“path/to/Test.html”“path/to/Test.html#no” ;在我看来,这使得链接在单击处理程序执行后window.location.assign()分配属性。window.location.href

在 Firefox (v72.0.2) 和 Chrome (v91.0.4472.106) 上测试

标签: javascripthtmlbrowserreloaddifference

解决方案


推荐阅读