如何在jQuery中在特定秒数后重新加载页面

如何在jQuery中在特定秒数后重新加载页面

在jQuery中,一个页面可以在特定的秒数后被重新加载,使用两种方法。

  • 使用location.reload()方法
  • 使用history.go(0)方法

使用location.reload()方法:该方法用于模仿浏览器的刷新按钮的动作来重新加载当前页面。它有一个可选的布尔参数,可以用来表示该页面是从服务器上重新加载的,而不是从浏览器的缓存中加载。

刷新代码可以通过setTimeout()函数在一定时间后执行。这个函数有一个延迟参数,表示该函数将执行的时间。这个值是以毫秒为单位的。要延迟的时间量以秒为单位乘以1000来转换为毫秒。

setTimeout代码可以在文档加载完毕后通过选择文档对象并对其使用ready()方法来调用。这将导致页面在指定的秒数后重新加载。

  • 语法:
$(document).ready(function () {
          setTimeout(function () {
            alert('Reloading Page');
            location.reload(true);
          }, 5000);
        });
  • 示例:
<!DOCTYPE html>
<html>
<head>
  <title>
    How to reload page after
    specific seconds?
  </title>
</head>
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <b>
    How to reload page after
    specific seconds?
  </b>
  <p>
    GeeksforGeeks is a computer science
    portal with a huge variety of well
    written and explained computer science
    and programming articles, quizzes and
    interview questions.
  </p>
  <p>
    The page will be reloaded in 5 seconds.
  </p>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js">
  </script>
   
  <script type="text/javascript">
    $(document).ready(function () {
      setTimeout(function () {
        alert('Reloading Page');
        location.reload(true);
      }, 5000);
    });
  </script>
</body>
</html>
  • 输出:
    加载页面后:
    如何在jQuery中在特定秒数后重新加载页面?

5秒后:
如何在jQuery中在特定秒数后重新加载页面?

使用history.go(0)方法:该方法根据传递给它的参数,从浏览器的历史中加载一个URL。如果传递的参数是’0’,它将重新加载当前页面。

刷新代码可以通过setTimeout()函数在一定时间后执行。这个函数有一个延迟参数,表示该函数将执行的时间。这个值是以毫秒为单位的。要延迟的时间量以秒为单位乘以1000来转换为毫秒。

这段代码可以在文档加载完毕后通过选择文档对象并对其使用 ready() 方法来调用。这将导致页面在指定的秒数后重新加载。

  • 语法:
$(document).ready(function () {
          setTimeout(function () {
            alert('Reloading Page');
            history.go(0);
          }, 5000);
        });
  • 示例:
<!DOCTYPE html>
<html>
<head>
    <title>
    How to reload page after
    specific seconds?
  </title>
</head>
<body>
  <h1 style="color: green">
    GeeksforGeeks
  </h1>
  <b>
    How to reload page after
    specific seconds?
  </b>
  <p>
    GeeksforGeeks is a computer science
    portal with a huge variety of well
    written and explained computer science
    and programming articles, quizzes and
    interview questions.
  </p>
  <p>
    The page will be reloaded in 5 seconds.
  </p>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js">
  </script>
  
  <script type="text/javascript">
    $(document).ready(function () {
      setTimeout(function () {
        alert('Reloading Page');
        history.go(0);
      }, 5000);
    });
  </script>
</body>
</html>

输出:

  • 在加载页面后。
    如何在jQuery中在特定秒数后重新加载页面?
    5秒后:
    如何在jQuery中在特定秒数后重新加载页面?

jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程