JQuery clearTimeOut没有停止setTimeOut无法正常工作

时间:2015-10-16 11:26:13

标签: jquery settimeout cleartimeout

我有一段简单的代码,只需点击一下按钮即可执行,但我需要检测一次双击(只需要点击一次 - 但我需要提醒两次或多次点击)。我有一个setTimeOut函数暂停一秒然后继续 - 但是我的代码应该清除这个函数不起作用,它执行alert()但不是停止setTimeOut功能!

$('.badge').on('click','#badge', function() {
    Click = Click + 1
    ButtonClick()
    if ($.isNumeric($(this).text())) {      
        $(this).css("background-color","#006400");
        BadgeNo = $(this).text()
        if (Click == 1) {
            var timeOut = setTimeout(function(){                
                $(this).css('background-color','#568bc1')
                $('.badge').hide()
                $('.hs').show()
                $('#numberplate').text('')
            }, 1000);
        } else if (Click > 1) {
            clearTimeout(timeOut);  
            alert("Please only select ONE badge number");
            CheckBadge();                   
        }
    }
});

我在这里犯了什么形式的小学生错误吗?我无法理解为什么它不会停止超时。

1 个答案:

答案 0 :(得分:3)

取消设置时var timeOut超出范围:

var timeOut = false;
$('.badge').on('click','#badge', function() {
    Click = Click + 1
    ButtonClick()
    if ($.isNumeric($(this).text())) {      
        $(this).css("background-color","#006400");
        BadgeNo = $(this).text()
        if (Click == 1) {
            timeOut = setTimeout(function(){                
                $(this).css('background-color','#568bc1')
                $('.badge').hide()
                $('.hs').show()
                $('#numberplate').text('')
            }, 1000);
        } else if (Click > 1) {
            if ( timeOut )
                 clearTimeout(timeOut);  
            alert("Please only select ONE badge number");
            CheckBadge();                   
        }
    }
});

仅对变量timeOut的范围及其初始化是否有轻微变化。

相关问题