javascript - jQuery - 5秒后重定向网页
问题描述
如果我在那里呆了一段时间,我想将我的页面重定向到另一个页面。我尝试编写以下脚本并将其放在网页的头部,但它不起作用。移动的位置不是真正的 url,因为我在 XAMPP 上。
$(document).ready(setTimeout(function () {
window.location.replace("../index.php");
}, 5000););
解决方案
您给出的方式完全错误,导致语法错误。检查您的控制台。该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);
});
推荐阅读
- python - 如何从字典中的项目连接到字符串
- javascript - 事件源;服务器发送的事件
- c# - 流数据的 CQRS
- c++ - 如何在 Windows 10 IOT 核心上的 Windows UWP 应用程序中运行外部 win32 可执行文件(并能够更新/修改它)?
- java - Java JFrame中用于电子邮件验证的while循环
- numpy - numpy.power() 崩溃了
- kubernetes - Helm 3 中共享 K8s Secrets 的最佳实践?
- ios - ScrollView惯性效果手动,iOS,Swift
- r - 将多个 .csv 文件的第一行复制到新的数据框中
- tus - 不要在 laravel 7 中安装 symfony/console v5.0.5 \ankitpokhrel/tus-php