0

我想取消由 javascript 函数启动的重定向。javascript 在 5 秒内重定向到主页,并显示为错误消息。我想通过鼠标单击错误消息来取消重定向。请提供任何帮助。

在此处输入图像描述

PHP代码:

<div id="error">    
<?php
    //redirect
    if (isset($_GET['err'])){
        if ($_GET['err'] == 1){
            echo "You are successfully logged out. You will be redirected to the home page in <strong><span id = 'seconds'> 5 </span> </strong> seconds.";
        }elseif($_GET['err'] == 0){
            echo "Your session has been expired. Please login again.!";
        }
    }
?>  
</div>

Javascript:

        <script>
        var seconds = 5;
        var err = <?php echo $_GET['err'] ; ?>;

        if (err == 1){
            setInterval(
            function(){
                if (seconds <= 1) {
                    window.location = 'http://****.***.***.***/***';
                }
                else {
                    document.getElementById('seconds').innerHTML = --seconds;
                }
                },
                1000
            );
        }
    </script>
4

4 回答 4

3

您实际上是在尝试停止 setInterval,您可以通过先命名它然后在您想要的条件下清除它来轻松地做到这一点。

var redirInt = setInterval(function() {
    // etc.
},5000);

还有你的取消线……</p>

clearInterval(redirInt);
于 2012-10-05T07:48:58.640 回答
1
var tId; // create a global var (or put it in a managed scope)
$(function() { // jquery onload
  tId = setInterval(function() { ... },5000); // or use timeout if no counter
  $("#errordiv").on("click",function() { 
    clearInterval(tId); // clear it
 });
});
于 2012-10-05T07:47:03.550 回答
1

setInterval返回它创建的计时器的 ID,以便您可以使用 取消它clearInterval

你可以使用这样的东西:

var timer;

$(document).ready(function() {
    timer = setInterval(function() {...}, 1000);

    $('#error').click(function() {
        clearInterval(timer);
    });
});
于 2012-10-05T07:49:35.297 回答
0

试试这个:

<script>

    var seconds = 5;
    var err = <?php echo $_GET['err'] ; ?>;
    var redir = null;

    if (err == 1){

        var redir_interval = setInterval(
        function(){
            if (seconds <= 1) {
                redir = window.location = 'http://****.***.***.***/***';
            }
            else {
                document.getElementById('seconds').innerHTML = --seconds;
            }
            },
            1000
        );
    }

    function cancel_redir() {

        redir = null;
        clearInterval(redir_interval);

    }

</script>

<div id="error" onclick="cancel_redir();">
You are successfully logged out. You will be redirected to the home page in <strong><span id = 'seconds'> 5 </span> </strong> seconds.
</div>
于 2012-10-05T07:49:22.513 回答