jQuery - 5 秒后重定向网页



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

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

你给出的方式是完全错误的,导致语法错误。检查您的主机。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);
});

你可以在没有JS的情况下做到这一点,方法是在标题中放置正确的元标记

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

其中"5"是等待超时。

最新更新