JavaScript 中 window.location.href、window.location.replace 和 window.location.assign 的区别?

javascriptobject oriented programmingfront end technology更新于 2024/6/27 2:52:17

JavaScript 中 window 对象包含 location 对象。它包含以下属性 −

window.location.href

它返回当前页面的 URL。

示例

<!DOCTYPE html>
<html>
   <body>
      <p>单击下面获取页面的完整 URL。</p>
      <button onclick = "display()">URL</button>
      <script>
          function display() {
            var res = location.href;
            document.write(res);
         }
      </script>
   </body>
</html>

window.location.replace

用于替换当前文档。

示例

<!DOCTYPE html>
<html>
   <body>
        <button onclick = "display()">替换当前文档</button>
      <script>
         function display() {
            location.replace("https://www.qries.com")
         }
      </script>
   </body>
</html>

window.location.assign

如果要加载新文档,请使用 JavaScript 分配。

示例

<!DOCTYPE html>
<html>
   <body>
      <button onclick = "display()">打开新文档</button>
      <script>
         function display() {
            location.assign("https://www.qries.com")
         }
        </script>
   </body>
</html>

相关文章


有用资源