jQuery-5秒后重定向网页

时间:2018-06-25 08:22:06

标签: javascript jquery redirect

如果我在页面上停留了一段时间,我想将页面重定向到另一个页面。我尝试编写以下脚本,并将其放在网页的开头,但它不起作用。因为我在xampp上,所以要移动的位置不是真实的URL。

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

2 个答案:

答案 0 :(得分:6)

您给出的方式完全错误,会导致语法错误。检查您的控制台。 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);
});

答案 1 :(得分:1)

您可以通过在标头中放置正确的元标记来实现,而无需使用JS

  angular: 5.0.0-alpha+13
  angular_components: 0.9.0-alpha+12

其中“ 5”是等待超时。

相关问题