首页 > 解决方案 > jQuery - 5秒后重定向网页

问题描述

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

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

标签: javascriptjqueryredirect

解决方案


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

试试这个方法:

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

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

如果你想在 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);
});

推荐阅读