2015-10-16 80 views
1

我有一個簡單的代碼,它執行一個按鈕的點擊,但我需要檢測雙擊(只需點擊一下 - 但我需要警惕兩個或更多點擊)。我有一個setTimeOut函數暫停一秒鐘,然後繼續前進 - 但我有代碼,應該清除此功能不起作用,它執行alert(),但不會停止setTimeOut函數!JQuery clearTimeOut不停止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();     
     } 
    } 
}); 

我在這兒做任何形式的小學生錯誤嗎?我只是不明白爲什麼它不能阻止超時。

回答

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的範圍和是否其初始化與否的細微變化。

+0

非常感謝@Axel Amthor--永遠不會爲我自己弄明白這一點,但它是一個很好的學習曲線,看看它應該是多麼的不同。乾杯! – Hyperjase