location

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head></head>

  <body>
    <button>点击</button>
    <div></div>

    <script>
      var btn = document.querySelector("button");
      var div = document.querySelector("div");
      console.log(123, location); // Location

      btn.addEventListener("click", function (e) {
        e.preventDefault;
        location.href = "http://www.itcast.cn";
      });

      var timer = 50;
      setInterval(function () {
        if (timer == 0) {
          location.href = "http://www.itcast.cn";
        } else {
          div.innerHTML = "您将在" + timer + "秒钟之后跳转到首页";
          timer--;
        }
      }, 1000);
    </script>
  </body>
</html>

location 常见的方法

<!DOCTYPE html>
<html lang="en">
  <head> </head>

  <body>
    <button>点击</button>

    <script>
      var btn = document.querySelector("button");
      btn.addEventListener("click", function () {
        // 记录浏览历史, 所以可以实现后退功能
        // location.assign('http://www.itcast.cn'); // 重定向

        // 不记录浏览历史, 所以不可以实现后退功能
        // location.replace('http://www.itcast.cn');

        // 刷新当前页面 true 强制刷新
        location.reload(true);
      });
    </script>
  </body>
</html>