【问题标题】:jQuery - Redirect webpage after 5 secondsjQuery - 5秒后重定向网页
【发布时间】:2018-06-25 08:22:06
【问题描述】:

如果我在那里停留一段时间,我想将我的页面重定向到另一个页面。我尝试编写以下脚本并将其放在网页的头部,但它不起作用。移动的位置不是真正的 url,因为我在 XAMPP 上。

$(document).ready(setTimeout(function () {
    window.location.replace("../index.php");
}, 5000););

【问题讨论】:

  • 即使你在 XAMPP 上,那怎么可能不是真正的 URL?
  • 如何使用 javascript 获取我的网址?
  • 使用location.href?

标签: javascript jquery redirect


【解决方案1】:

您给出的方式完全错误,导致语法错误。检查您的控制台。 ready() 函数需要一个函数而不是整数(由 setTimeout() 返回)。

试试这个方法:

$(function () {
  setTimeout(function() {
    window.location.replace("../index.php");
  }, 5000);
});

或者,如果您只想在 5 秒不活动后使用,则需要使用不同的方法检查用户活动(keypressmousemove),然后清除计时器并重新启动它。

如果您想在 5 秒不活动后尝试重定向,您可以这样做:

var timer = 0;
function startRedirect() {
  timer = setTimeout(function () {
    window.location.replace("../index.php");
  }, 5000);
}
function restartTimer() {
  clearTimeout(timer);
  startRedirect();
}
$(function () {
  startRedirect();
  $(document).mousemove(restartTimer).keyup(restartTimer);
});

【讨论】:

    【解决方案2】:

    你可以在没有 JS 的情况下通过将正确的元标记放入标题中来做到这一点

    <head>
       <meta http-equiv="Refresh" content="5; url=http://google.com">
    </head>
    

    其中“5”是等待超时。

    【讨论】:

    • I want to redirect my page to another one if I stay there for a certain time. - 这肯定使用了一些条件。您的将在 5 秒后自动重定向。听起来是不是不对?
    • 对对,这里需要JS来处理条件状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多