在鼠标单击事件上取消javascript重定向

时间:2012-10-05 07:43:04

标签: javascript redirect

我想取消由javascript函数启动的重定向。 javascript会在5秒内重定向到主页,并显示为错误消息。我想在鼠标单击错误消息时取消重定向。请帮忙。

enter image description here

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 个答案:

答案 0 :(得分:3)

您实际上是在尝试停止setInterval,您可以通过先命名然后以所需的条件清除它来轻松完成。

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

和你的取消线......

clearInterval(redirInt);

答案 1 :(得分: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
 });
});

答案 2 :(得分:1)

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

您可以使用以下内容:

var timer;

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

    $('#error').click(function() {
        clearInterval(timer);
    });
});

答案 3 :(得分: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>