JQuery - 5秒后重定向网页

Enn*_*nio -1 javascript jquery redirect

如果我在那里停留一段时间,我想将我的页面重定向到另一个页面.我试着写下面的脚本,我把它放在我的网页的头部,但它不起作用.移动的局部地址不是真正的网址,因为我在xampp上.

    <script>
        $( document ).ready(setTimeout(function() {
            window.location.replace("../index.php");
        }, 5000););
    </script>
Run Code Online (Sandbox Code Playgroud)

Pra*_*man 6

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

试试这种方式:

$(function () {
  setTimeout(function() {
    window.location.replace("../index.php");
  }, 5000);
});
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想在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);
});
Run Code Online (Sandbox Code Playgroud)